Refactor REPL

This commit is contained in:
백현웅 2022-01-13 00:54:40 +09:00
parent 1fd0b30b41
commit b05605558c

45
main.ml
View file

@ -1,31 +1,44 @@
open Printf open Printf
exception Reset_line (* used to indicate ^C is pressed *)
let version = "%%VERSION%%"
let error_to_string e = let error_to_string e =
try raise e with try raise e with
| Parser.Expected t -> sprintf "expected %s" t | Parser.Expected t -> sprintf "expected %s" t
| Parser.Unexpected_token t -> sprintf "unexpected token \"%s\"" t | Parser.Unexpected_token t -> sprintf "unexpected token \"%s\"" t
| Failure f -> f | Failure f -> sprintf "error on %s" f
| Division_by_zero -> "cannot divide by zero" | Division_by_zero -> "cannot divide by zero"
| _ -> raise e | _ -> raise e
let print_error e = let print_error e =
printf "error: %s\n" @@ error_to_string e printf "error: %s\n" @@ error_to_string e
(* simple REPL *) (* read-eval-print *)
let rec repl () : unit = let rep () : unit =
printf "> "; printf "> ";
let line = read_line () in let line = read_line () in
if line <> "quit" then begin if line = "quit" then raise Exit;
(try line
line |> Lex.tokenize
|> Lex.tokenize |> Parser.parse
|> Parser.parse |> Eval.eval
|> Eval.eval |> Ast.typ_to_string
|> Ast.typ_to_string |> printf "%s\n"
|> printf "%s\n"
with
| e -> print_error e);
repl ()
end
let () = repl () let init_repl () =
let sigintf _ = raise Reset_line in
Sys.(set_signal sigint (Signal_handle sigintf))
(* simple REPL with error handling *)
let rec repl () : unit =
try rep (); repl () with
| Exit | End_of_file -> ()
| Reset_line -> printf "\n"; repl ()
| e -> print_error e; repl ()
let () =
init_repl ();
printf "Configurable Evaluator %s\n" version; (* banner *)
repl ()