Skip to content

Instantly share code, notes, and snippets.

@garybernhardt
Created March 1, 2015 05:19
Show Gist options
  • Save garybernhardt/47279f49ec895b780f9b to your computer and use it in GitHub Desktop.
Save garybernhardt/47279f49ec895b780f9b to your computer and use it in GitHub Desktop.
open Parser;;
open Stringutil;;
type t = String of string | List of t list
let rec of_module m =
List (String "module" :: of_definitions m)
and of_definitions ds =
List.map of_definition ds
and of_definition (FuncDef func_def) =
List [String "definition"; of_func_def func_def]
and of_func_def ((Ident ident), matches) =
List [String ("func_def " ^ ident); of_matches matches]
and of_matches ms =
List [String "matches"; List (List.map of_match ms)]
and of_match = function
(pattern, exp) -> List [String "match"; (of_exp pattern); (of_exp exp)]
and of_exp e =
match e with
| Literal literal -> of_literal literal
| Block block -> of_block block
| PrefixExp exp -> of_prefix_exp exp
| Operator op -> of_operator op
and of_literal n =
match n with
| False -> String "false"
| True -> String "true"
| Number number -> String (string_of_int number)
| String str -> String str
and of_block (arg_names, exp) =
List [String "block"; of_arg_names arg_names; of_exp exp]
and of_prefix_exp n =
match n with
| Ident ident -> of_ident ident
| FuncCall func_call -> of_func_call func_call
and of_operator n =
match n with
| Binary (left, right) -> List [String "binary"; of_exp left; of_exp right]
| Unary exp -> List [String "unary"; of_exp exp]
and of_arg_names n =
List [String "arg_names"; List (List.map of_ident n)]
and of_ident (Ident s) = String s
and of_func_call (prefix_exp, exp_list) =
List [String "func_call"; of_prefix_exp prefix_exp; of_exp_list exp_list]
and of_exp_list n = List (String "exp_list" :: List.map of_ident n)
;;
let rec sexp_to_string s indent =
match s with
| String str -> (string_repeat " " (indent * 2)) ^ str ^ "\n"
| List elements -> join (List.map (fun s -> sexp_to_string s (indent + 1)) elements)
;;
let module_to_string m = "Parse tree:\n" ^ sexp_to_string (of_module m) 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment