From dae562047c9970a652b40d30dc1753cb5494ad40 Mon Sep 17 00:00:00 2001 From: Hyeonung Baek Date: Tue, 11 Jan 2022 00:45:25 +0900 Subject: [PATCH] Add error handling --- main.ml | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/main.ml b/main.ml index 7580f02..384827b 100644 --- a/main.ml +++ b/main.ml @@ -1,14 +1,30 @@ +open Printf + +let error_to_string e = + try raise e with + | Parser.Expected t -> sprintf "expected %s" t + | Parser.Unexpected_token t -> sprintf "unexpected token \"%s\"" t + | Failure f -> f + | Division_by_zero -> "cannot divide by zero" + | _ -> raise e + +let print_error e = + printf "error: %s\n" @@ error_to_string e + (* simple REPL *) let rec repl () : unit = - Printf.printf "> "; + printf "> "; let line = read_line () in if line <> "quit" then begin - line - |> Lex.tokenize - |> Parser.parse - |> Eval.eval - |> Ast.typ_to_string - |> Printf.printf "%s\n"; + try + line + |> Lex.tokenize + |> Parser.parse + |> Eval.eval + |> Ast.typ_to_string + |> printf "%s\n" + with + | e -> print_error e; repl () end