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 + : "