-
Notifications
You must be signed in to change notification settings - Fork 1
/
miniml.ml
58 lines (52 loc) · 1.52 KB
/
miniml.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
(*
CS 51 Final Project
MiniML -- Read-Eval-Print Loop
Spring 2017
*)
module Ev = Evaluation ;;
module MP = Miniml_parse ;;
module ML = Miniml_lex ;;
module Ex = Expr ;;
open Printf ;;
(* str_to_exp: string -> expr
Returns the expression specified by the string using the Miniml
parser. *)
let str_to_exp (str: string) : Ex.expr =
let lexbuf = Lexing.from_string str in
let exp = MP.input ML.token lexbuf in
exp
;;
(* repl: unit -> unit
Read-eval-print loop for MiniML. *)
let repl () =
(* lexical analyzer buffer from stdin *)
let lexbuf = Lexing.from_channel stdin in
(* set up the initial environment *)
let env = Ev.Env.create () in
printf "Entering %s...\n" Sys.argv.(0);
flush stdout;
while true do
(try
(* prompt *)
printf "<== ";
flush stdout;
(* read and parse an expression from the input *)
let exp = MP.input ML.token lexbuf in
(* evaluate it *)
let res = Ev.evaluate exp env in
(* print the result *)
printf "==> %s\n" (Ev.Env.value_to_string ~printenvp:false res)
with
| Parsing.Parse_error -> printf "xx> parse error\n"
| Ev.EvalError msg -> printf "xx> evaluation error: %s\n" msg
| Ev.EvalException -> printf "xx> evaluation exception\n"
| End_of_file -> printf "Goodbye.\n"; exit 0
);
flush stdout
done
;;
(* Run repl if called from command line *)
try
let _ = Str.search_forward (Str.regexp "miniml\\.\\(byte\\|native\\)") (Sys.argv.(0)) 0 in
repl ()
with Not_found -> () ;;