From b29331c24659eccf6ae9cc003f7d276ab02bc4de Mon Sep 17 00:00:00 2001 From: monoid Date: Wed, 29 Jan 2025 20:44:36 +0900 Subject: [PATCH] feat: tab indent `expr2str` --- lib/eval.ml | 3 --- lib/parser.ml | 21 +++++++++++---------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/eval.ml b/lib/eval.ml index 8f1f7cb..b958f2f 100644 --- a/lib/eval.ml +++ b/lib/eval.ml @@ -1,8 +1,5 @@ - - module VariableBindingMap = Map.Make(String) - type value_type = | Int of int | Fun of function_type diff --git a/lib/parser.ml b/lib/parser.ml index a55d181..d0ff5ae 100644 --- a/lib/parser.ml +++ b/lib/parser.ml @@ -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