Allow adding strings

This commit is contained in:
Stanisław Barzowski 2017-07-28 17:23:27 -04:00
parent 70da0b879d
commit 964c4bc0df
2 changed files with 22 additions and 4 deletions

View File

@ -360,6 +360,21 @@ func (i *interpreter) objectIndex(loc *LocationRange, obj value, f string, offse
} }
} }
func (i *interpreter) evalAdd(leftVal, rightVal value) (value, error) {
switch leftVal := leftVal.(type) {
case *valueNumber:
left := leftVal.value
right := rightVal.(*valueNumber).value
return makeValueNumber(left + right), nil
case *valueString:
left := leftVal.value
right := rightVal.(*valueString).value
return makeValueString(left + right), nil
}
// TODO(sbarzowski) More types and more graceful error handling
panic("unknown type")
}
func (i *interpreter) evaluate(a astNode) (value, error) { func (i *interpreter) evaluate(a astNode) (value, error) {
// TODO(dcunnin): All the other cases... // TODO(dcunnin): All the other cases...
switch ast := a.(type) { switch ast := a.(type) {
@ -374,19 +389,21 @@ func (i *interpreter) evaluate(a astNode) (value, error) {
return &valueArray{elements}, nil return &valueArray{elements}, nil
case *astBinary: case *astBinary:
// TODO(dcunnin): Assume it's + on numbers for now // TODO(dcunnin): Assume it's + for now
leftVal, err := i.evaluate(ast.left) leftVal, err := i.evaluate(ast.left)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// TODO(dcunnin): Check the type properly. The following code just panics. // TODO(dcunnin): Check the type properly. The following code just panics.
leftNum := leftVal.(*valueNumber).value
rightVal, err := i.evaluate(ast.right) rightVal, err := i.evaluate(ast.right)
if err != nil { if err != nil {
return nil, err return nil, err
} }
rightNum := rightVal.(*valueNumber).value result, err := i.evalAdd(leftVal, rightVal)
return makeValueNumber(leftNum + rightNum), nil if err != nil {
return nil, err
}
return result, nil
case *astDesugaredObject: case *astDesugaredObject:
// Evaluate all the field names. Check for null, dups, etc. // Evaluate all the field names. Check for null, dups, etc.

View File

@ -36,6 +36,7 @@ var mainTests = []mainTest{
{"simple_arith1", "3 + 3", "6", ""}, {"simple_arith1", "3 + 3", "6", ""},
{"simple_arith2", "3 + 3 + 3", "9", ""}, {"simple_arith2", "3 + 3 + 3", "9", ""},
{"simple_arith3", "(3 + 3) + (3 + 3)", "12", ""}, {"simple_arith3", "(3 + 3) + (3 + 3)", "12", ""},
{"simple_arith_string", "\"aaa\" + \"bbb\"", "\"aaabbb\"", ""},
{"empty_array", "[]", "[ ]", ""}, {"empty_array", "[]", "[ ]", ""},
{"array", "[1, 2, 1 + 2]", "[\n 1,\n 2,\n 3\n]", ""}, {"array", "[1, 2, 1 + 2]", "[\n 1,\n 2,\n 3\n]", ""},
{"empty_object", "{}", "{ }", ""}, {"empty_object", "{}", "{ }", ""},