Chapter 29.2
This commit is contained in:
parent
726803c9d0
commit
1bba129074
1 changed files with 18 additions and 0 deletions
|
@ -71,6 +71,7 @@ typedef struct Compiler {
|
||||||
|
|
||||||
typedef struct ClassCompiler {
|
typedef struct ClassCompiler {
|
||||||
struct ClassCompiler *enclosing;
|
struct ClassCompiler *enclosing;
|
||||||
|
bool hasSuperclass;
|
||||||
} ClassCompiler;
|
} ClassCompiler;
|
||||||
|
|
||||||
static int resolveUpvalue(Compiler *, Token *);
|
static int resolveUpvalue(Compiler *, Token *);
|
||||||
|
@ -478,6 +479,13 @@ static void variable(bool canAssign) {
|
||||||
namedVariable(parser.previous, 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() {
|
static void classDeclaration() {
|
||||||
consume(TOKEN_IDENTIFIER, "Expect class name");
|
consume(TOKEN_IDENTIFIER, "Expect class name");
|
||||||
Token className = parser.previous;
|
Token className = parser.previous;
|
||||||
|
@ -488,6 +496,7 @@ static void classDeclaration() {
|
||||||
defineVariable(nameConstant);
|
defineVariable(nameConstant);
|
||||||
|
|
||||||
ClassCompiler classCompiler;
|
ClassCompiler classCompiler;
|
||||||
|
classCompiler.hasSuperclass = false;
|
||||||
classCompiler.enclosing = currentClass;
|
classCompiler.enclosing = currentClass;
|
||||||
currentClass = &classCompiler;
|
currentClass = &classCompiler;
|
||||||
|
|
||||||
|
@ -499,8 +508,13 @@ static void classDeclaration() {
|
||||||
error("A class can't inherit from itself.");
|
error("A class can't inherit from itself.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
beginScope();
|
||||||
|
addLocal(syntheticToken("super"));
|
||||||
|
defineVariable(0);
|
||||||
|
|
||||||
namedVariable(className, false);
|
namedVariable(className, false);
|
||||||
emitByte(OP_INHERIT);
|
emitByte(OP_INHERIT);
|
||||||
|
classCompiler.hasSuperclass = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
namedVariable(className, false);
|
namedVariable(className, false);
|
||||||
|
@ -511,6 +525,10 @@ static void classDeclaration() {
|
||||||
consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");
|
consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");
|
||||||
emitByte(OP_POP);
|
emitByte(OP_POP);
|
||||||
|
|
||||||
|
if (classCompiler.hasSuperclass) {
|
||||||
|
endScope();
|
||||||
|
}
|
||||||
|
|
||||||
currentClass = currentClass->enclosing;
|
currentClass = currentClass->enclosing;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue