diff options
Diffstat (limited to 'src/bytecode/chunk.c')
-rw-r--r-- | src/bytecode/chunk.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/bytecode/chunk.c b/src/bytecode/chunk.c new file mode 100644 index 0000000..3dc2421 --- /dev/null +++ b/src/bytecode/chunk.c | |||
@@ -0,0 +1,43 @@ | |||
1 | #include "chunk.h" | ||
2 | #include "objects.h" | ||
3 | |||
4 | Chunk * | ||
5 | chunk_init(void) { | ||
6 | Chunk *chunk = malloc(sizeof(Chunk)); | ||
7 | array_init(chunk->code, 0); | ||
8 | array_init(chunk->constants, 0); | ||
9 | array_init(chunk->lines, 0); | ||
10 | return chunk; | ||
11 | } | ||
12 | |||
13 | void | ||
14 | chunk_free(Chunk *chunk) { | ||
15 | array_free(chunk->code); | ||
16 | for (size_t i = 0; i < array_size(chunk->constants); i++) { | ||
17 | Object obj = chunk->constants[i]; | ||
18 | object_free(obj); | ||
19 | } | ||
20 | array_free(chunk->constants); | ||
21 | array_free(chunk->lines); | ||
22 | free(chunk); | ||
23 | } | ||
24 | |||
25 | void | ||
26 | add_code(Chunk *chunk, u8 byte, size_t line, size_t col) { | ||
27 | array_push(chunk->code, byte); | ||
28 | LineInfo info = (LineInfo){line, col}; | ||
29 | array_push(chunk->lines, info); | ||
30 | } | ||
31 | |||
32 | size_t | ||
33 | add_constant(Chunk *chunk, Object obj) { | ||
34 | size_t pos = array_size(chunk->constants); | ||
35 | for (size_t i = 0; i < pos; i++) { | ||
36 | if (object_equal(obj, chunk->constants[i])) { | ||
37 | return i; | ||
38 | } | ||
39 | } | ||
40 | array_push(chunk->constants, obj); | ||
41 | return pos; | ||
42 | } | ||
43 | |||