aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/chunk.h
blob: 81fc4cc3dca47bbe142ede0e071e3edac9d1b39d (plain)
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
#ifndef BDL_CHUNK_H
#define BDL_CHUNK_H

#include "objects.h"
#include "darray.h"

typedef struct LineInfo {
    size_t line;
    size_t col;
} LineInfo;

typedef struct Chunk {
    u8 *code;
    Object *constants;
    LineInfo *lines;
} Chunk;

Chunk * chunk_init(void);
void add_code(Chunk *chunk, u8 byte, size_t line, size_t col);
size_t add_constant(Chunk *chunk, Object obj);
void chunk_free(Chunk *chunk);

Chunk *
chunk_init(void) {
    Chunk *chunk = malloc(sizeof(Chunk));
    array_init(chunk->code, 0);
    array_init(chunk->constants, 0);
    array_init(chunk->lines, 0);
    return chunk;
}

void
chunk_free(Chunk *chunk) {
    array_free(chunk->code);
    array_free(chunk->constants);
    array_free(chunk->lines);
    free(chunk);
}

void
add_code(Chunk *chunk, u8 byte, size_t line, size_t col) {
    array_push(chunk->code, byte);
    LineInfo info = (LineInfo){line, col};
    array_push(chunk->lines, info);
}

size_t
add_constant(Chunk *chunk, Object obj) {
    // FIXME?: Since we are using a single byte to store constant indices, we
    // can only have 256 stored constants. If we need more we may need to add
    // another instruction OP_CONSTANT_16 to have at least two bytes for
    // constants. Alternatively, we could make that the default. Either way, for
    // now it's fine.
    size_t pos = array_size(chunk->constants);
    array_push(chunk->constants, obj);
    return pos;
}

#endif // BDL_CHUNK_H