Skip to content

Commit abdfd2e

Browse files
authored
fix this keyword reference outside of classes (#135)
1 parent 0d176ae commit abdfd2e

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

evaluator/evaluator_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,37 @@ func TestInheritedProperties(t *testing.T) {
372372
}
373373
}
374374

375+
func TestThisOutsideClass(t *testing.T) {
376+
tests := []struct {
377+
name string
378+
input string
379+
expected string
380+
}{
381+
{
382+
name: "this at top level",
383+
input: `this`,
384+
expected: "1:1:test.ghost: runtime error: 'this' used outside of class context",
385+
},
386+
{
387+
name: "this in regular function",
388+
input: `function foo() { return this } foo()`,
389+
expected: "1:25:test.ghost: runtime error: 'this' used outside of class context",
390+
},
391+
{
392+
name: "this.property at top level",
393+
input: `this.name`,
394+
expected: "1:1:test.ghost: runtime error: 'this' used outside of class context",
395+
},
396+
}
397+
398+
for _, tt := range tests {
399+
t.Run(tt.name, func(t *testing.T) {
400+
result := evaluate(tt.input)
401+
isErrorObject(t, result, tt.expected)
402+
})
403+
}
404+
}
405+
375406
// =============================================================================
376407
// Helper functions
377408

evaluator/this.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@ import (
66
)
77

88
func evaluateThis(node *ast.This, scope *object.Scope) object.Object {
9-
if scope.Self != nil {
9+
switch scope.Self.(type) {
10+
case *object.Instance, *object.Class:
1011
return scope.Self
1112
}
1213

13-
pairs := make(map[object.MapKey]object.MapPair)
14-
15-
return &object.Map{Pairs: pairs}
14+
return newError("%d:%d:%s: runtime error: 'this' used outside of class context", node.Token.Line, node.Token.Column, node.Token.File)
1615
}

0 commit comments

Comments
 (0)