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 + ()