Add assert function to stdlib. Useful for tests

This commit is contained in:
Konstantin Nazarov 2024-08-27 20:19:47 +01:00
parent 7ea2c3e193
commit 781b3865c0
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
3 changed files with 14 additions and 0 deletions

View file

@ -17,6 +17,7 @@ enum class ErrorCode {
ArgumentCountMismatch, ArgumentCountMismatch,
IOError, IOError,
Interrupt, Interrupt,
AssertionFailed,
}; };
void seterr(const char* err); void seterr(const char* err);

View file

@ -53,6 +53,17 @@ Result<Value> stdlib_println(const Array& params) {
Result<Value> stdlib_prn(const Array& params) { return ERROR(NotImplemented); } Result<Value> stdlib_prn(const Array& params) { return ERROR(NotImplemented); }
Result<Value> stdlib_assert(const Array& params) {
for (uint64_t i = 0; i < params.size(); i++) {
Value param = TRY(params.get(i));
if (!param.is<Bool>()) return ERROR(AssertionFailed);
auto v = param.to<Bool>()->value();
if (!v) return ERROR(AssertionFailed);
}
return Value(TRY(Nil::create()));
}
#define STDLIB_FUNCTION(name, id) \ #define STDLIB_FUNCTION(name, id) \
[(uint64_t)StdlibFunctionId::id] = {#name, StdlibFunctionId::id, \ [(uint64_t)StdlibFunctionId::id] = {#name, StdlibFunctionId::id, \
stdlib_##name} stdlib_##name}
@ -62,6 +73,7 @@ static StdlibFunctionEntry function_entries[] = {
STDLIB_FUNCTION(print, Print), STDLIB_FUNCTION(print, Print),
STDLIB_FUNCTION(println, PrintLn), STDLIB_FUNCTION(println, PrintLn),
STDLIB_FUNCTION(prn, Prn), STDLIB_FUNCTION(prn, Prn),
STDLIB_FUNCTION(assert, Assert),
[(uint64_t)StdlibFunctionId::Max] = {0, StdlibFunctionId::Max, [(uint64_t)StdlibFunctionId::Max] = {0, StdlibFunctionId::Max,
stdlib_unknown}, stdlib_unknown},
}; };

View file

@ -9,6 +9,7 @@ enum class StdlibFunctionId : uint64_t {
Print, Print,
PrintLn, PrintLn,
Prn, Prn,
Assert,
Max, Max,
}; };