ce/ast.ml

66 lines
1.6 KiB
OCaml
Raw Permalink Normal View History

2022-02-01 21:38:00 +09:00
(* simple, untyped AST. *)
type t =
2022-02-17 02:51:56 +09:00
| Nothing
2022-02-24 19:57:26 +09:00
| Nunit
| Nint of int
| Nfloat of float
2022-02-08 16:05:33 +09:00
| Nbool of bool
| Nstring of string
2022-02-08 00:26:03 +09:00
| Nsymbol of string
2022-02-22 17:01:39 +09:00
| Nfunction of string list * t
| Nexternal of string
2022-02-01 21:38:00 +09:00
| Var of string
| Let of string * t
2022-02-09 17:27:19 +09:00
| Letin of string * t * t
2022-02-01 21:38:00 +09:00
| Unary of operator * t
| Binop of t * operator * t
2022-02-08 16:05:33 +09:00
| If of t * t * t (* cond then else *)
2022-02-01 21:38:00 +09:00
| Apply of t * t list (* function application *)
2022-02-24 02:31:29 +09:00
and operator = string
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
2022-02-17 02:51:56 +09:00
| Nothing -> pr ""
2022-02-24 19:57:26 +09:00
| Nunit -> pr "()"
| Nint n -> pr "%d" n
| Nfloat n -> pr "%f" n
2022-02-08 16:05:33 +09:00
| Nbool b -> pr "%b" b
| Nstring s -> pr "\"%s\"" s
2022-02-08 00:26:03 +09:00
| Nsymbol s -> pr "#%s" s
2022-02-22 17:01:39 +09:00
| Nfunction (arg::args, e) ->
pr "(lambda (%s" arg;
List.iter (pr " %s") args;
2022-02-08 16:05:33 +09:00
pr ") "; aux e; pr ")"
| Nexternal e -> pr "(extern %s)" e
2022-02-09 17:27:19 +09:00
2022-01-19 14:17:04 +09:00
| Var v -> pr "%s" v
2022-02-23 02:45:36 +09:00
| Let (v, Nfunction (args, e)) ->
pr "(define (%s" v;
List.iter (pr " %s") args;
pr ") "; aux e; pr ")"
2022-01-21 00:17:01 +09:00
| Let (v, e) ->
2022-02-09 17:27:19 +09:00
pr "(define %s " v; aux e; pr ")"
| Letin (v, e, f) ->
2022-02-17 02:51:56 +09:00
pr "(let ((%s " v; aux e; pr ")) "; aux f; pr ")"
2022-01-29 20:01:48 +09:00
| Unary (op, t) ->
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-01 21:38:00 +09:00
pr "(%s " op; aux left; pr " "; aux right; pr ")"
2022-02-08 16:05:33 +09:00
| If (co, th, el) ->
let f e = pr " "; aux e in
pr "(if"; f co; f th; f el; pr ")"
2022-01-29 20:01:48 +09:00
| Apply (f, args) ->
2022-02-08 16:05:33 +09:00
pr "("; aux f; List.iter (fun a -> pr " "; aux a) args; pr ")"
2022-02-22 17:01:39 +09:00
| _ -> invalid_arg "Ast.print"
2022-01-10 01:31:47 +09:00
in
aux ast; pr "\n"