File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed
Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -249,6 +249,8 @@ func evalInfixExpression(
249249 // The check for integer operands has to be higher up in the switch
250250 // statement.
251251 return evalIntegerInfixExpression (operator , left , right )
252+ case left .Type () == object .STRING_OBJ && right .Type () == object .STRING_OBJ :
253+ return evalStringInfixExpression (operator , left , right )
252254 case operator == "==" :
253255 // Using pointer comparison to check for equality between booleans.
254256 return nativeBoolToBooleanObject (left == right )
@@ -294,6 +296,23 @@ func evalIntegerInfixExpression(
294296 }
295297}
296298
299+ func evalStringInfixExpression (
300+ operator string ,
301+ left , right object.Object ,
302+ ) object.Object {
303+ // Check for the correct operator.
304+ if operator != "+" {
305+ return newError ("unknown operator: %s %s %s" ,
306+ left .Type (), operator , right .Type ())
307+ }
308+
309+ // Unwrap the string objects and construct a new string that's a
310+ // concatenation of both operands.
311+ leftVal := left .(* object.String ).Value
312+ rightVal := right .(* object.String ).Value
313+ return & object.String {Value : leftVal + rightVal }
314+ }
315+
297316func evalIfExpression (
298317 ie * ast.IfExpression ,
299318 env * object.Environment ,
Original file line number Diff line number Diff line change @@ -206,6 +206,10 @@ func TestErrorHandling(t *testing.T) {
206206 "5; true + false; 5" ,
207207 "unknown operator: BOOLEAN + BOOLEAN" ,
208208 },
209+ {
210+ `"Hello" - "World"` ,
211+ "unknown operator: STRING - STRING" ,
212+ },
209213 {
210214 "if (10 > 1) { true + false; }" ,
211215 "unknown operator: BOOLEAN + BOOLEAN" ,
@@ -345,6 +349,20 @@ func TestStringLiteral(t *testing.T) {
345349 }
346350}
347351
352+ func TestStringConcatenation (t * testing.T ) {
353+ input := `"Hello" + " " + "World!"`
354+
355+ evaluated := testEval (input )
356+ str , ok := evaluated .(* object.String )
357+ if ! ok {
358+ t .Fatalf ("object is not String. got=%T (%+v)" , evaluated , evaluated )
359+ }
360+
361+ if str .Value != "Hello World!" {
362+ t .Errorf ("String has wrong value. got=%q" , str .Value )
363+ }
364+ }
365+
348366func testEval (input string ) object.Object {
349367 l := lexer .New (input )
350368 p := parser .New (l )
You can’t perform that action at this time.
0 commit comments