Skip to content

Commit

Permalink
String concatenation now a thing.
Browse files Browse the repository at this point in the history
  • Loading branch information
tjlawal committed May 9, 2023
1 parent 2637863 commit c0253cb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
16 changes: 14 additions & 2 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,8 @@ func Eval(node ast.Node, env *object.Environment) object.Object {
}
return apply_function(function, args)


case *ast.StringLiteral:
return &object.String { Value: node.Value }
return &object.String{Value: node.Value}
}

return nil
Expand Down Expand Up @@ -232,6 +231,9 @@ func eval_infix_expression(operator string, left object.Object, right object.Obj

case left.Type() != right.Type():
return new_error("type mismatch: %s %s %s", left.Type(), operator, right.Type())

case left.Type() == object.STRING_OBJECT && right.Type() == object.STRING_OBJECT:
return eval_string_infix_expression(operator, left, right)
default:
return new_error("unknown operator: %s %s %s", left.Type(), operator, right.Type())
}
Expand Down Expand Up @@ -287,6 +289,16 @@ func eval_if_expression(ie *ast.IfExpression, env *object.Environment) object.Ob
}
}

func eval_string_infix_expression(operator string, left, right object.Object) object.Object {
if operator != "+" {
return new_error("unknown operator: %s %s %s", left.Type(), operator, right.Type())
}

left_value := left.(*object.String).Value
right_value := right.(*object.String).Value
return &object.String{Value: left_value + right_value}
}

func is_truthy(object object.Object) bool {
switch object {
case NULL:
Expand Down
18 changes: 18 additions & 0 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ func TestErrorHandling(l_test *testing.T) {
}
`, "unknown operator: BOOLEAN + BOOLEAN"},
{"foobar", "identifier not found: foobar"},
{
`"Hello" - "World"`,
"unknown operator: STRING - STRING",
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -252,6 +256,20 @@ func TestStringLiteral(l_test *testing.T) {
}
}

func TestStringConcatenation(l_test *testing.T) {
input := `"Hello" + " " + "World!"`

evaluated := test_eval(input)
string, ok := evaluated.(*object.String)
if !ok {
l_test.Fatalf("object is not String. got=%T (%+v)", evaluated, evaluated)
}

if string.Value != "Hello World!" {
l_test.Errorf("String has wrong value. got=%q", string.Value)
}
}

// Helpers
func test_eval(input string) object.Object {
l_lexer := lexer.New(input)
Expand Down

0 comments on commit c0253cb

Please sign in to comment.