From dbb3b6ac2a07a0a696e36d0e02f2c7d6fdb4c2a8 Mon Sep 17 00:00:00 2001 From: "Shea Lewis (Kai)" <355659+kaidesu@users.noreply.github.com> Date: Tue, 13 Jan 2026 00:01:37 -0800 Subject: [PATCH] fix this keyword reference outside of classes --- evaluator/evaluator_test.go | 31 +++++++++++++++++++++++++++++++ evaluator/this.go | 7 +++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/evaluator/evaluator_test.go b/evaluator/evaluator_test.go index e1a1824..a200231 100644 --- a/evaluator/evaluator_test.go +++ b/evaluator/evaluator_test.go @@ -372,6 +372,37 @@ func TestInheritedProperties(t *testing.T) { } } +func TestThisOutsideClass(t *testing.T) { + tests := []struct { + name string + input string + expected string + }{ + { + name: "this at top level", + input: `this`, + expected: "1:1:test.ghost: runtime error: 'this' used outside of class context", + }, + { + name: "this in regular function", + input: `function foo() { return this } foo()`, + expected: "1:25:test.ghost: runtime error: 'this' used outside of class context", + }, + { + name: "this.property at top level", + input: `this.name`, + expected: "1:1:test.ghost: runtime error: 'this' used outside of class context", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := evaluate(tt.input) + isErrorObject(t, result, tt.expected) + }) + } +} + // ============================================================================= // Helper functions diff --git a/evaluator/this.go b/evaluator/this.go index 2d3bb5e..7723af4 100644 --- a/evaluator/this.go +++ b/evaluator/this.go @@ -6,11 +6,10 @@ import ( ) func evaluateThis(node *ast.This, scope *object.Scope) object.Object { - if scope.Self != nil { + switch scope.Self.(type) { + case *object.Instance, *object.Class: return scope.Self } - pairs := make(map[object.MapKey]object.MapPair) - - return &object.Map{Pairs: pairs} + return newError("%d:%d:%s: runtime error: 'this' used outside of class context", node.Token.Line, node.Token.Column, node.Token.File) }