ce/main.ml
2022-01-13 00:54:40 +09:00

44 lines
1 KiB
OCaml

open Printf
exception Reset_line (* used to indicate ^C is pressed *)
let version = "%%VERSION%%"
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 -> sprintf "error on %s" f
| Division_by_zero -> "cannot divide by zero"
| _ -> raise e
let print_error e =
printf "error: %s\n" @@ error_to_string e
(* read-eval-print *)
let rep () : unit =
printf "> ";
let line = read_line () in
if line = "quit" then raise Exit;
line
|> Lex.tokenize
|> Parser.parse
|> Eval.eval
|> Ast.typ_to_string
|> printf "%s\n"
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 ()