#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]; object_free(obj); } 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) { size_t pos = array_size(chunk->constants); for (size_t i = 0; i < pos; i++) { if (object_equal(obj, chunk->constants[i])) { return i; } } array_push(chunk->constants, obj); return pos; } #endif // BDL_CHUNK_H