From ebc35cb133623b26c7cd3290234d3f7451143590 Mon Sep 17 00:00:00 2001 From: Elijah Cohen Date: Tue, 24 Dec 2024 17:26:18 -0800 Subject: [PATCH] random uint --- src/builtins.c | 2 ++ src/builtins/io.c | 25 ++++++++++++++++++++++++- src/builtins/io.h | 3 +++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/builtins.c b/src/builtins.c index dfe2052..65f577b 100644 --- a/src/builtins.c +++ b/src/builtins.c @@ -220,6 +220,8 @@ char* lookup_builtin(Sexpr* b) { return IO_READFILE_STR; case IO_WRITEFILE: return IO_WRITEFILE_STR; + case IO_RAND: + return IO_RAND_STR; default: return "NOT FOUND (IO)"; } diff --git a/src/builtins/io.c b/src/builtins/io.c index 1887966..3531add 100644 --- a/src/builtins/io.c +++ b/src/builtins/io.c @@ -125,6 +125,26 @@ Sexpr* io_writefile(Sexpr* b, Sexpr* rest, Sexpr* env) { return cons(from_uint(num_written), rest); } +Sexpr* io_rand(Sexpr* b, Sexpr* rest, Sexpr* env) { + if(IO_RAND_ARGS != u64_get_num_args(b)) { + return cons(b, rest); + } + Sexpr* args = b->value.b.args; + Sexpr* arg = eval(clone(car(args)), env); +#ifdef TYPECHECK + if(arg->type != UINT) { + ERR(IO_RAND_STR ": ", "argument not uint"); + sexpr_free(arg); + sexpr_free(b); + return cons(from_nil(), rest); + } +#endif + K_UINT_TYPE m = unquote(arg)->value.u; + sexpr_free(b); + sexpr_free(arg); + return cons(from_uint(rand() % m), rest); +} + Sexpr* x_io_dispatch(Sexpr* b, Sexpr* rest, Sexpr* env) { uint64_t code = b->value.b.opcode & 0xff; @@ -140,6 +160,8 @@ Sexpr* x_io_dispatch(Sexpr* b, Sexpr* rest, Sexpr* env) { return io_readfile(b, rest, env); case IO_WRITEFILE: return io_writefile(b, rest, env); + case IO_RAND: + return io_rand(b, rest, env); default: return from_nil(); } @@ -152,6 +174,7 @@ Sexpr* load_io_env(Sexpr* env) { load_builtin(IO_PB_STR, (IO_PREFIX << 8) | IO_PB, env); load_builtin(IO_READFILE_STR, (IO_PREFIX << 8) | IO_READFILE, env); load_builtin(IO_WRITEFILE_STR, (IO_PREFIX << 8) | IO_WRITEFILE, env); - + load_builtin(IO_RAND_STR, (IO_PREFIX << 8) | IO_RAND, env); + return env; } diff --git a/src/builtins/io.h b/src/builtins/io.h index 2d0b42b..44de27a 100644 --- a/src/builtins/io.h +++ b/src/builtins/io.h @@ -20,6 +20,9 @@ #define IO_WRITEFILE 0x04 #define IO_WRITEFILE_ARGS 2 #define IO_WRITEFILE_STR "writefile" +#define IO_RAND 0x05 +#define IO_RAND_ARGS 1 +#define IO_RAND_STR "rand" Sexpr* x_io_dispatch(Sexpr* s, Sexpr* rest, Sexpr* env); Sexpr* load_io_env(Sexpr* env); -- 2.39.2