diff options
Diffstat (limited to 'clox/src/vm.c')
-rw-r--r-- | clox/src/vm.c | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/clox/src/vm.c b/clox/src/vm.c index 0d8d638..bf7078c 100644 --- a/clox/src/vm.c +++ b/clox/src/vm.c @@ -1,6 +1,7 @@ #include <stdarg.h> #include <stdio.h> #include <string.h> +#include <time.h> #include "common.h" #include "compiler.h" @@ -11,6 +12,10 @@ VM vm; +static Value clockNative(int argCount, Value *args) { + return NUMBER_VAL((double)clock() / CLOCKS_PER_SEC); +} + static void resetStack() { vm.stackTop = vm.stack; vm.frameCount = 0; @@ -38,12 +43,22 @@ static void runtimeError(const char *format, ...) { resetStack(); } +static void defineNative(const char *name, NativeFn function) { + push(OBJ_VAL(copyString(name, (int)strlen(name)))); + push(OBJ_VAL(newNative(function))); + tableSet(&vm.globals, AS_STRING(vm.stack[0]), vm.stack[1]); + pop(); + pop(); +} + void initVM() { resetStack(); vm.objects = NULL; initTable(&vm.globals); initTable(&vm.strings); + + defineNative("clock", clockNative); } void freeVM() { @@ -88,6 +103,13 @@ static bool callValue(Value callee, int argCount) { switch (OBJ_TYPE(callee)) { case OBJ_FUNCTION: return call(AS_FUNCTION(callee), argCount); + case OBJ_NATIVE: { + NativeFn native = AS_NATIVE(callee); + Value result = native(argCount, vm.stackTop - argCount); + vm.stackTop -= argCount + 1; + push(result); + return true; + } default: break; } |