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 {
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue