From 1bba129074b812a354eccfdd9cc69b233789dc6c Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Sun, 14 Aug 2022 22:27:35 -0700 Subject: Chapter 29.2 --- clox/src/compiler.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/clox/src/compiler.c b/clox/src/compiler.c index f14666c..599ad1b 100644 --- a/clox/src/compiler.c +++ b/clox/src/compiler.c @@ -71,6 +71,7 @@ typedef struct Compiler { typedef struct ClassCompiler { struct ClassCompiler *enclosing; + bool hasSuperclass; } ClassCompiler; static int resolveUpvalue(Compiler *, Token *); @@ -478,6 +479,13 @@ static void variable(bool canAssign) { namedVariable(parser.previous, canAssign); } +static Token syntheticToken(const char *text) { + Token token; + token.start = text; + token.length = (int)strlen(text); + return token; +} + static void classDeclaration() { consume(TOKEN_IDENTIFIER, "Expect class name"); Token className = parser.previous; @@ -488,6 +496,7 @@ static void classDeclaration() { defineVariable(nameConstant); ClassCompiler classCompiler; + classCompiler.hasSuperclass = false; classCompiler.enclosing = currentClass; currentClass = &classCompiler; @@ -499,8 +508,13 @@ static void classDeclaration() { error("A class can't inherit from itself."); } + beginScope(); + addLocal(syntheticToken("super")); + defineVariable(0); + namedVariable(className, false); emitByte(OP_INHERIT); + classCompiler.hasSuperclass = true; } namedVariable(className, false); @@ -511,6 +525,10 @@ static void classDeclaration() { consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body."); emitByte(OP_POP); + if (classCompiler.hasSuperclass) { + endScope(); + } + currentClass = currentClass->enclosing; } -- cgit v1.2.3-54-g00ecf