Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 3 additions & 4 deletions evaluator/this.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}