Finish Chapter 14

Implements code chunks, a couple of basic opcodes, constants, and
basic execution of those opcodes.

Signed-off-by: Daniel Henry <iamdanhenry@gmail.com>
This commit is contained in:
2025-08-21 16:14:22 -05:00
commit 44c7626cd7
13 changed files with 286 additions and 0 deletions

25
include/chunk.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef clox_chunk_h
#define clox_chunk_h
#include "common.h"
#include "value.h"
typedef enum {
OP_CONSTANT,
OP_RETURN,
} OpCode;
typedef struct {
int count;
int capacity;
uint8_t *code;
int *lines;
ValueArray constants;
} Chunk;
void initChunk(Chunk *chunk);
void freeChunk(Chunk *chunk);
void writeChunk(Chunk *chunk, uint8_t byte, int line);
int addConstant(Chunk *chunk, Value value);
#endif /* clox_chunk_h */

8
include/common.h Normal file
View File

@@ -0,0 +1,8 @@
#ifndef clox_common_h
#define clox_common_h
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#endif

9
include/debug.h Normal file
View File

@@ -0,0 +1,9 @@
#ifndef clox_debug_h
#define clox_debug_h
#include "chunk.h"
void disassembleChunk(Chunk *chunk, const char *name);
int disassembleInstruction(Chunk *chunk, int offset);
#endif /* clox_debug_h */

15
include/memory.h Normal file
View File

@@ -0,0 +1,15 @@
#ifndef clox_memory_h
#define clox_memory_h
#include "common.h"
#define GROW_CAPACITY(capacity) ((capacity) < 8 ? 8 : (capacity) * 2)
#define GROW_ARRAY(type, pointer, oldCount, newCount) \
(type *)reallocate(pointer, sizeof(type) * (oldCount), \
sizeof(type) * (newCount))
#define FREE_ARRAY(type, pointer, oldCount) \
reallocate(pointer, sizeof(type) * oldCount, 0);
void *reallocate(void *pointer, size_t oldSize, size_t newSize);
#endif /* clox_memory_h */

19
include/value.h Normal file
View File

@@ -0,0 +1,19 @@
#ifndef clox_value_h
#define clox_value_h
#include "common.h"
typedef double Value;
typedef struct {
int capacity;
int count;
Value *values;
} ValueArray;
void initValueArray(ValueArray *array);
void writeValueArray(ValueArray *array, Value value);
void freeValueArray(ValueArray *array);
void printValue(Value value);
#endif /* clox_value_h */