Skip to content

Commit

Permalink
4.4 Arrays (evaluating array literals)
Browse files Browse the repository at this point in the history
  • Loading branch information
cedrickchee committed Apr 1, 2020
1 parent 375deda commit bda181a
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
7 changes: 7 additions & 0 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ func Eval(node ast.Node, env *object.Environment) object.Object {

// Call the function. Apply the function to the arguments.
return applyFunction(function, args)

case *ast.ArrayLiteral:
elements := evalExpressions(node.Elements, env)
if len(elements) == 1 && isError(elements[0]) {
return elements[0]
}
return &object.Array{Elements: elements}
}

return nil
Expand Down
19 changes: 19 additions & 0 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,25 @@ func TestBuiltinFunctions(t *testing.T) {
}
}

func TestArrayLiterals(t *testing.T) {
input := "[1, 2 * 2, 3 + 3]"

evaluated := testEval(input)
result, ok := evaluated.(*object.Array)
if !ok {
t.Fatalf("object is not Array. got=%T (%+v)", evaluated, evaluated)
}

if len(result.Elements) != 3 {
t.Fatalf("array has wrong num of elements. got=%d",
len(result.Elements))
}

testIntegerObject(t, result.Elements[0], 1)
testIntegerObject(t, result.Elements[1], 4)
testIntegerObject(t, result.Elements[2], 6)
}

func testEval(input string) object.Object {
l := lexer.New(input)
p := parser.New(l)
Expand Down
27 changes: 27 additions & 0 deletions object/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ const (

// BUILTIN_OBJ is the Builtin object type.
BUILTIN_OBJ = "BUILTIN"

// ARRAY_OBJECT is the Array object type.
ARRAY_OBJ = "ARRAY"
)

// BuiltinFunction represents the builtin function type.
Expand Down Expand Up @@ -175,3 +178,27 @@ func (b *Builtin) Type() ObjectType { return BUILTIN_OBJ }

// Inspect returns a stringified version of the object for debugging.
func (b *Builtin) Inspect() string { return "builtin function" }

// Array is the array literal type that holds a slice of Object(s).
type Array struct {
Elements []Object
}

// Type returns the type of the object
func (ao *Array) Type() ObjectType { return ARRAY_OBJ }

// Inspect returns a stringified version of the object for debugging.
func (ao *Array) Inspect() string {
var out bytes.Buffer

elements := []string{}
for _, e := range ao.Elements {
elements = append(elements, e.Inspect())
}

out.WriteString("[")
out.WriteString(strings.Join(elements, ", "))
out.WriteString("]")

return out.String()
}

0 comments on commit bda181a

Please sign in to comment.