forked from vkazanov/bytecode-interpreters-post
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter-basic-switch.c
More file actions
83 lines (70 loc) · 1.61 KB
/
interpreter-basic-switch.c
File metadata and controls
83 lines (70 loc) · 1.61 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>
struct {
uint8_t *ip;
uint64_t accumulator;
} vm;
typedef enum {
/* increment the register */
OP_INC,
/* decrement the register */
OP_DEC,
/* stop execution */
OP_DONE
} opcode;
typedef enum interpret_result {
SUCCESS,
ERROR_UNKNOWN_OPCODE,
} interpret_result;
void vm_reset(void)
{
puts("Reset vm state");
vm = (typeof(vm)) { NULL };
}
interpret_result vm_interpret(uint8_t *bytecode)
{
vm_reset();
puts("Start interpreting");
vm.ip = bytecode;
for (;;) {
uint8_t instruction = *vm.ip++;
switch (instruction) {
case OP_INC: {
vm.accumulator++;
break;
}
case OP_DEC: {
vm.accumulator--;
break;
}
case OP_DONE: {
return SUCCESS;
}
default:
return ERROR_UNKNOWN_OPCODE;
}
}
return SUCCESS;
}
int main(int argc, char *argv[])
{
(void) argc; (void) argv;
{
uint8_t code[] = { OP_INC, OP_INC, OP_DEC, OP_DONE };
interpret_result result = vm_interpret(code);
printf("vm state: %" PRIu64 "\n", vm.accumulator);
assert(result == SUCCESS);
assert(vm.accumulator == 1);
}
{
uint8_t code[] = { OP_INC, OP_DEC, OP_DEC, OP_DONE };
interpret_result result = vm_interpret(code);
printf("vm state: %" PRIu64 "\n", vm.accumulator);
assert(result == SUCCESS);
assert(vm.accumulator == UINT64_MAX);
}
return EXIT_SUCCESS;
}