Merge pull request #15 from sbarzowski/strings

Allow adding strings
This commit is contained in:
Dave Cunningham 2017-08-01 19:54:12 -04:00 committed by GitHub
commit f81573cb4e
2 changed files with 26 additions and 4 deletions

View File

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

View File

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