From e62d1a209e352306f36879dadd85773167e06246 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Sun, 18 Apr 2021 17:29:25 -0700 Subject: [PATCH] 12.5.1 Invalid uses of this --- src/com/craftinginterpreters/lox/Resolver.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/com/craftinginterpreters/lox/Resolver.java b/src/com/craftinginterpreters/lox/Resolver.java index f68e4dc..70c5970 100644 --- a/src/com/craftinginterpreters/lox/Resolver.java +++ b/src/com/craftinginterpreters/lox/Resolver.java @@ -18,6 +18,13 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { NONE, FUNCTION, METHOD } + private enum ClassType { + NONE, + CLASS + } + + private ClassType currentClass = ClassType.NONE; + public void resolve(List statements) { for (Stmt statement : statements) { resolve(statement); @@ -34,6 +41,9 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { @Override public Void visitClassStmt(Stmt.Class stmt) { + ClassType enclosingClass = currentClass; + currentClass = ClassType.CLASS; + declare(stmt.name); define(stmt.name); @@ -47,6 +57,7 @@ class Resolver implements Expr.Visitor, Stmt.Visitor { endScope(); + currentClass = enclosingClass; return null; } @@ -161,6 +172,12 @@ 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."); + return null; + } + resolveLocal(expr, expr.keyword); return null; }