[jlox] Parse superclass

This commit is contained in:
ctsk
2022-10-11 12:07:44 +02:00
parent 5729dbc010
commit 6d20bb63c2
2 changed files with 11 additions and 4 deletions

View File

@@ -14,7 +14,8 @@ import static xyz.ctsk.lox.TokenType.*;
* | funDecl * | funDecl
* | varDecl * | varDecl
* | statement ; * | statement ;
* classDecl → "class" IDENTIFIER "{" function* "}" ; * classDecl → "class" IDENTIFIER ( "<" IDENTIFIER )?
* "{" function* "}" ;
* funDecl → "fun" function ; * funDecl → "fun" function ;
* function → IDENTIFIER "(" parameters? ")" block ; * function → IDENTIFIER "(" parameters? ")" block ;
* parameters → IDENTIFIER ( "," IDENTIFIER )* ; * parameters → IDENTIFIER ( "," IDENTIFIER )* ;
@@ -87,6 +88,13 @@ public class Parser {
private Stmt classDeclaration() { private Stmt classDeclaration() {
var name = consume(IDENTIFIER, "Expect class name."); var name = consume(IDENTIFIER, "Expect class name.");
Expr.Variable superclass = null;
if (match(LESS)) {
consume(IDENTIFIER, "Expect superclass name.");
superclass = new Expr.Variable(previous());
}
consume(LEFT_BRACE, "Expect '{' before class body."); consume(LEFT_BRACE, "Expect '{' before class body.");
List<Stmt.Function> methods = new ArrayList<>(); List<Stmt.Function> methods = new ArrayList<>();
@@ -96,8 +104,7 @@ public class Parser {
} }
consume(LEFT_BRACE, "Expect '}' after class body."); consume(LEFT_BRACE, "Expect '}' after class body.");
return new Stmt.Class(name, methods); return new Stmt.Class(name, superclass, methods);
} }
private Stmt.Function function(FunctionType kind) { private Stmt.Function function(FunctionType kind) {

View File

@@ -16,7 +16,7 @@
@Root(name = "Stmt", @Root(name = "Stmt",
rules = { rules = {
@Rule(head = "Block", body = {"List<Stmt> statements"}), @Rule(head = "Block", body = {"List<Stmt> statements"}),
@Rule(head = "Class", body = {"Token name", "List<Stmt.Function> methods"}), @Rule(head = "Class", body = {"Token name", "Expr.Variable superclass", "List<Stmt.Function> methods"}),
@Rule(head = "Expression", body = {"Expr expression"}), @Rule(head = "Expression", body = {"Expr expression"}),
@Rule(head = "Function", body = {"Token name", "List<Token> params", "List<Stmt> body"}), @Rule(head = "Function", body = {"Token name", "List<Token> params", "List<Stmt> body"}),
@Rule(head = "If", body = {"Expr condition", "Stmt thenBranch", "Stmt elseBranch"}), @Rule(head = "If", body = {"Expr condition", "Stmt thenBranch", "Stmt elseBranch"}),