diff options
| author | Bobby <[email protected]> | 2024-04-04 14:08:33 +0000 |
|---|---|---|
| committer | Bobby <[email protected]> | 2024-04-04 14:08:33 +0000 |
| commit | 2f28a8de055029c4501a8cfb796e7f4a1af8b719 (patch) | |
| tree | 6769c43d4abfb20412f40617d77cd9ffc9bad263 /evaluator | |
| parent | cf6dd4b0e5efa1f8041d5570497a5228c737c454 (diff) | |
| download | mana-2f28a8de055029c4501a8cfb796e7f4a1af8b719.tar.xz mana-2f28a8de055029c4501a8cfb796e7f4a1af8b719.zip | |
added string concatenation
Diffstat (limited to 'evaluator')
| -rw-r--r-- | evaluator/evaluator.go | 13 | ||||
| -rw-r--r-- | evaluator/evaluator_test.go | 18 |
2 files changed, 31 insertions, 0 deletions
diff --git a/evaluator/evaluator.go b/evaluator/evaluator.go index 9129a98..0eadd92 100644 --- a/evaluator/evaluator.go +++ b/evaluator/evaluator.go @@ -198,6 +198,8 @@ func evalInfixExpression(operator string, left, right object.Object) object.Obje switch { case left.Type() == object.INTEGER_OBJ && right.Type() == object.INTEGER_OBJ: return evalIntegerInfixExpression(operator, left, right) + case left.Type() == object.STRING_OBJ && right.Type() == object.STRING_OBJ: + return evalStringInfixExpression(operator, left, right) case operator == "==": return nativeBoolToBooleanObject(left == right) case operator == "!=": @@ -260,6 +262,17 @@ func evalIntegerInfixExpression(operator string, left, right object.Object) obje } } +func evalStringInfixExpression(operator string, left, right object.Object) object.Object { + if operator != "+" { + return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) + } + + leftVal := left.(*object.String).Value + rightVal := right.(*object.String).Value + + return &object.String{Value: leftVal + rightVal} +} + func evalIfExpression(ie *ast.IfExpression, env *object.Environment) object.Object { condition := Eval(ie.Condition, env) if isError(condition) { diff --git a/evaluator/evaluator_test.go b/evaluator/evaluator_test.go index cf9e320..9738d9e 100644 --- a/evaluator/evaluator_test.go +++ b/evaluator/evaluator_test.go @@ -181,6 +181,10 @@ func TestErrorhandling(t *testing.T) { "foobar", "identifier not found: foobar", }, + { + `"Hello" - "World"`, + "unknown operator: STRING - STRING", + }, } for _, tt := range tests { @@ -327,3 +331,17 @@ func TestStringLiteral(t *testing.T) { t.Errorf("String has wrong value. got=%q", str.Value) } } + +func TestStringConcatenation(t *testing.T) { + input := `"Hello" + " " + "World!"` + + evaluated := testEval(input) + str, ok := evaluated.(*object.String) + if !ok { + t.Fatalf("object is not String. got=%T (%+v)", evaluated, evaluated) + } + + if str.Value != "Hello World!" { + t.Errorf("String has wrong value. got=%q", str.Value) + } +} |
