#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); for (size_t i = 0; i < array_size(chunk->constants); i++) { Object obj = chunk->constants[i]; if (IS_STRING(obj) || IS_SYMBOL(obj)) { array_free(obj.text); } } 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