From e74cbddb0463e93f5d9742accc20bbed027d0b9b Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Tue, 31 May 2022 23:02:18 -0700 Subject: Chapter 25.2 --- clox/src/compiler.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) (limited to 'clox/src/compiler.c') diff --git a/clox/src/compiler.c b/clox/src/compiler.c index 7500005..6e98b5e 100644 --- a/clox/src/compiler.c +++ b/clox/src/compiler.c @@ -44,6 +44,11 @@ typedef struct { int depth; } Local; +typedef struct { + uint8_t index; + bool isLocal; +} Upvalue; + typedef enum { TYPE_FUNCTION, TYPE_SCRIPT } FunctionType; typedef struct Compiler { @@ -53,9 +58,12 @@ typedef struct Compiler { Local locals[UINT8_COUNT]; int localCount; + Upvalue upvalues[UINT8_COUNT]; int scopeDepth; } Compiler; +static int resolveUpvalue(Compiler *, Token *); + Parser parser; Compiler *current = NULL; Chunk *compilingChunk; @@ -340,6 +348,11 @@ static void function(FunctionType type) { ObjFunction *function = endCompiler(); emitBytes(OP_CLOSURE, makeConstant(OBJ_VAL(function))); + + for (int i = 0; i < function->upvalueCount; i++) { + emitByte(compiler.upvalues[i].isLocal ? 1 : 0); + emitByte(compiler.upvalues[i].index); + } } static void markInitialized() { @@ -567,6 +580,9 @@ static void namedVariable(Token name, bool canAssign) { if (arg != -1) { getOp = OP_GET_LOCAL; setOp = OP_SET_LOCAL; + } else if ((arg = resolveUpvalue(current, &name)) != -1) { + getOp = OP_GET_UPVALUE; + setOp = OP_SET_UPVALUE; } else { arg = identifierConstant(&name); getOp = OP_GET_GLOBAL; @@ -698,6 +714,43 @@ static int resolveLocal(Compiler *compiler, Token *name) { return -1; } +static int addUpvalue(Compiler *compiler, uint8_t index, bool isLocal) { + int upvalueCount = compiler->function->upvalueCount; + + for (int i = 0; i < upvalueCount; i++) { + Upvalue *upvalue = &compiler->upvalues[i]; + if (upvalue->index == index && upvalue->isLocal == isLocal) { + return i; + } + } + + if (upvalueCount == UINT8_COUNT) { + error("Too many closure variables in function."); + return 0; + } + + compiler->upvalues[upvalueCount].isLocal = isLocal; + compiler->upvalues[upvalueCount].index = index; + return compiler->function->upvalueCount++; +} + +static int resolveUpvalue(Compiler *compiler, Token *name) { + if (compiler->enclosing == NULL) + return -1; + + int local = resolveLocal(compiler->enclosing, name); + if (local != -1) { + return addUpvalue(compiler, (uint8_t)local, true); + } + + int upvalue = resolveUpvalue(compiler->enclosing, name); + if (upvalue != -1) { + return addUpvalue(compiler, (uint8_t)upvalue, false); + } + + return -1; +} + static void addLocal(Token name) { if (current->localCount == UINT8_COUNT) { error("Too many local variables in function."); -- cgit v1.2.3-54-g00ecf