From 8f4b95a13704540792225753820ec05e873b9039 Mon Sep 17 00:00:00 2001 From: Moritz Gmeiner Date: Wed, 28 Aug 2024 17:19:34 +0200 Subject: [PATCH] added loxstd with clock and exit --- lib/dune | 1 + lib/loxstd.ml | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 lib/loxstd.ml diff --git a/lib/dune b/lib/dune index b021fd5..8d0ada5 100644 --- a/lib/dune +++ b/lib/dune @@ -1,5 +1,6 @@ (library (name Lox) + (libraries unix) (preprocess (pps ppx_deriving.show))) diff --git a/lib/loxstd.ml b/lib/loxstd.ml new file mode 100644 index 0000000..b35f4bf --- /dev/null +++ b/lib/loxstd.ml @@ -0,0 +1,28 @@ +open Environment +open Value + +let clock : native_function = + let fn = function + | [] -> + let time = Unix.gettimeofday () in + Number time |> Result.ok + | _ -> assert false + in + { name = "clock"; arity = 0; fn } + +let exit : native_function = + let fn = function + | [ n ] -> ( + match n with + | Number n when Float.is_integer n -> Int.of_float n |> exit + | _ -> + Printf.sprintf "Must call exit with integer, received %s instead" (show_lox_value n) + |> Result.error) + | _ -> assert false + in + { name = "exit"; arity = 1; fn } + +let init_std (env : environment) = + let register_fn fn = Env.define_global env fn.name (Function (NativeFunction fn)) in + let _ = List.map register_fn [ clock; exit ] in + ()