Skip to content

Commit cedbd76

Browse files
committed
feat: Add core virtual machine implementation with stack, global variables, and instruction dispatch for bytecode execution.
1 parent 8c03bf0 commit cedbd76

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/runtime/vm.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,41 @@ static InterpretResult run(VM *vm) {
463463
frame->ip -= offset;
464464
break;
465465
}
466+
case OP_CALL: {
467+
int argCount = READ_BYTE();
468+
Value callee = peek(vm, argCount);
469+
if (IS_CLOSURE(callee)) {
470+
ObjClosure* closure = AS_CLOSURE(callee);
471+
if (argCount != closure->function->arity) {
472+
runtimeError(vm, "Expected %d arguments but got %d.", closure->function->arity, argCount);
473+
return INTERPRET_RUNTIME_ERROR;
474+
}
475+
if (vm->frameCount == 64) {
476+
runtimeError(vm, "Stack overflow.");
477+
return INTERPRET_RUNTIME_ERROR;
478+
}
479+
frame = &vm->frames[vm->frameCount++];
480+
frame->closure = closure;
481+
frame->ip = closure->function->chunk.code;
482+
frame->slots = vm->stackTop - argCount - 1;
483+
break;
484+
} else if (IS_NATIVE(callee)) {
485+
NativeFn native = AS_NATIVE(callee);
486+
Value result = native(argCount, vm->stackTop - argCount);
487+
vm->stackTop -= argCount + 1;
488+
push(vm, result);
489+
break;
490+
} else {
491+
runtimeError(vm, "Can only call functions and classes.");
492+
return INTERPRET_RUNTIME_ERROR;
493+
}
494+
}
495+
case OP_CLOSURE: {
496+
ObjFunction* function = AS_FUNCTION(READ_CONSTANT());
497+
ObjClosure* closure = newClosure(function);
498+
push(vm, OBJ_VAL(closure));
499+
break;
500+
}
466501
case OP_RETURN: {
467502
vm->frameCount--;
468503
if (vm->frameCount == 0) {

0 commit comments

Comments
 (0)