From 958ba22a570594ed2ce60d24cd082ce3b8a6b89a Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Sat, 12 Jun 2021 12:17:43 -0700 Subject: 12.7 Constructors and Initializers --- src/com/craftinginterpreters/lox/Resolver.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'src/com/craftinginterpreters/lox/Resolver.java') diff --git a/src/com/craftinginterpreters/lox/Resolver.java b/src/com/craftinginterpreters/lox/Resolver.java index 70c5970..cda0f60 100644 --- a/src/com/craftinginterpreters/lox/Resolver.java +++ b/src/com/craftinginterpreters/lox/Resolver.java @@ -15,12 +15,11 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { } private enum FunctionType { - NONE, FUNCTION, METHOD + NONE, FUNCTION, INITIALIZER, METHOD } private enum ClassType { - NONE, - CLASS + NONE, CLASS } private ClassType currentClass = ClassType.NONE; @@ -52,6 +51,9 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { for (Stmt.Function method : stmt.methods) { FunctionType declaration = FunctionType.METHOD; + if (method.name.lexeme.equals("init")) { + declaration = FunctionType.INITIALIZER; + } resolveFunction(method, declaration); } @@ -98,6 +100,9 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { } if (stmt.value != null) { + if (currentFunction == FunctionType.INITIALIZER) { + Lox.error(stmt.keyword, "Can't return a value from an initializer."); + } resolve(stmt.value); } @@ -173,8 +178,7 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { @Override public Void visitThisExpr(Expr.This expr) { if (currentClass == ClassType.NONE) { - Lox.error(expr.keyword, - "Can't use 'this' outside of a class."); + Lox.error(expr.keyword, "Can't use 'this' outside of a class."); return null; } -- cgit v1.2.3-54-g00ecf