-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm.c
61 lines (51 loc) · 955 Bytes
/
vm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "chunk.h"
#include "vm.h"
#include "compiler.h"
#include "value.h"
VM vm;
void initVM() {
vm.chunk = NULL;
vm.ip = NULL;
vm.stackTop = vm.stack;
}
void push(Value value) {
*vm.stackTop = value;
vm.stackTop++;
}
Value pop() {
vm.stackTop--;
return *vm.stackTop;
}
static int run() {
#define READ_BYTE() (*vm.ip++)
for (;;) {
uint8_t instruction;
switch (instruction = READ_BYTE()) {
case OP_CONSTANT: {
Value constant = vm.chunk->constants.values[READ_BYTE()];
push(constant);
break;
}
case OP_PRINT: {
printf("%d", pop());
printf("\n");
break;
}
case OP_RETURN: {
return 0;
}
}
}
#undef READ_BYTE
}
int interpret(const char* source) {
Chunk chunk;
initChunk(&chunk);
int result = compile(source, &chunk);
vm.chunk = &chunk;
vm.ip = vm.chunk->code;
if(result == 1) {
return 1;
}
return run();
}