From a52c55eb9af3e29a912d41a48071e830b0971fd5 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Sat, 22 Jan 2022 22:01:54 -0800 Subject: Chapter 24.2 (Does Not Compile) --- clox/src/compiler.c | 36 +++++++++++++++++++++++++++--------- clox/src/compiler.h | 2 +- clox/src/object.c | 4 ++++ 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/clox/src/compiler.c b/clox/src/compiler.c index aed21f7..44eede8 100644 --- a/clox/src/compiler.c +++ b/clox/src/compiler.c @@ -44,7 +44,12 @@ typedef struct { int depth; } Local; +typedef enum { TYPE_FUNCTION, TYPE_SCRIPT } FunctionType; + typedef struct { + ObjFunction *function; + FunctionType type; + Local locals[UINT8_COUNT]; int localCount; int scopeDepth; @@ -54,7 +59,7 @@ Parser parser; Compiler *current = NULL; Chunk *compilingChunk; -static Chunk *currentChunk() { return compilingChunk; } +static Chunk *currentChunk() { return ¤t->function->chunk; } static void errorAt(Token *token, const char *message) { if (parser.panicMode) @@ -165,19 +170,33 @@ static void patchJump(int offset) { currentChunk()->code[offset + 1] = jump & 0xff; } -static void initCompiler(Compiler *compiler) { +static void initCompiler(Compiler *compiler, FunctionType type) { + compiler->function = NULL; + compiler->type = type; compiler->localCount = 0; compiler->scopeDepth = 0; + compiler->function = newFunction(); current = compiler; + + Local *local = ¤t->locals[current->localCount++]; + local->depth = 0; + local->name.start = ""; + local->name.length = 0; } -static void endCompiler() { +static ObjFunction *endCompiler() { emitReturn(); + ObjFunction *function = current->function; + #ifdef DEBUG_PRINT_CODE if (!parser.hadError) { - disassembleChunk(currentChunk(), "code"); + disassembleChunk(currentChunk(), function->name != NULL + ? function->name->chars + : "