added loxstd with clock and exit

This commit is contained in:
Moritz Gmeiner 2024-08-28 17:19:34 +02:00
commit 8f4b95a137
2 changed files with 29 additions and 0 deletions

View file

@ -1,5 +1,6 @@
(library
(name Lox)
(libraries unix)
(preprocess
(pps ppx_deriving.show)))

28
lib/loxstd.ml Normal file
View file

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