feat: tab indent expr2str

This commit is contained in:
monoid 2025-01-29 20:44:36 +09:00
parent 57d1cc73dd
commit b29331c246
2 changed files with 11 additions and 13 deletions

View file

@ -1,8 +1,5 @@
module VariableBindingMap = Map.Make(String)
type value_type =
| Int of int
| Fun of function_type

View file

@ -94,17 +94,18 @@ and expr_tree =
| Number of int
let expr2str (e: expr_tree): string =
let rec aux e =
let tab n = String.make (n * 2) ' ' in
let rec aux e depth =
match e with
| LetExpr (Let (id, e1, e2)) -> Printf.sprintf "let %s = %s in\n %s" id (aux e1) (aux e2)
| FunExpr (Fun (id, e)) -> Printf.sprintf "fun %s -> %s" id (aux e)
| IfExpr (If (e1, e2, e3)) -> Printf.sprintf "if %s then %s else %s" (aux e1) (aux e2) (aux e3)
| CallExpr (Call (e1, e2)) -> Printf.sprintf "%s %s" (aux e1) (aux e2)
| BinOpExpr (op, e1, e2) -> Printf.sprintf "%s %s %s" (aux e1) (Lexer.op2str op) (aux e2)
| MonoOpExpr (op, e) -> Printf.sprintf "%s %s" (Lexer.op2str op) (aux e)
| LetExpr (Let (id, e1, e2)) -> Printf.sprintf "let %s = %s in\n%s%s" id (aux e1 depth) (tab depth) (aux e2 (depth+1))
| FunExpr (Fun (id, e)) -> Printf.sprintf "fun %s ->\n%s%s" id (tab depth) (aux e (depth+1))
| IfExpr (If (e1, e2, e3)) -> Printf.sprintf "if %s then\n%s%selse\n%s%s" (aux e1 depth) (tab depth) (aux e2 depth) (tab depth) (aux e3 depth)
| CallExpr (Call (e1, e2)) -> Printf.sprintf "%s %s" (aux e1 depth) (aux e2 depth)
| BinOpExpr (op, e1, e2) -> Printf.sprintf "%s %s %s" (aux e1 depth) (Lexer.op2str op) (aux e2 depth)
| MonoOpExpr (op, e) -> Printf.sprintf "%s %s" (Lexer.op2str op) (aux e depth)
| Identifier id -> id
| Number n -> string_of_int n in
aux e
aux e 0
let rec parse_let_expr (): let_expr_tree parser =
let* _ = match_token (Lexer.Keyword Lexer.Let) in
@ -212,8 +213,8 @@ let get_expr_tree_from_tokens (tokens: Lexer.token Seq.t): expr_tree option =
| None -> None
let%test "test get_expr_tree_from_tokens 1" =
let tokens = Lexer.lex_tokens_seq "let x = 1 in x" in
let tokens = Lexer.lex_tokens_seq "let x = 1 in\n x" in
let tokens = tokens |> Seq.map (fun (x,_) -> x) in
match get_expr_tree_from_tokens tokens with
| Some e -> expr2str e = "let x = 1 in\n x"
| Some e -> expr2str e = "let x = 1 in\n x"
| None -> false