Add error handling

This commit is contained in:
백현웅 2022-01-11 00:45:25 +09:00
parent 4e0d4dd9ac
commit dae562047c

30
main.ml
View file

@ -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