array literals
Some checks failed
Build / build (push) Failing after 2m16s
Test / build (push) Failing after 1m46s

This commit is contained in:
Chuck Smith
2024-02-26 15:47:24 -05:00
parent e4bca02235
commit 8721665bc1
5 changed files with 105 additions and 0 deletions

View File

@@ -133,12 +133,34 @@ func (vm *VM) Run() error {
return err
}
case code.OpArray:
numElements := int(code.ReadUint16(vm.instructions[ip+1:]))
ip += 2
array := vm.buildArray(vm.sp-numElements, vm.sp)
vm.sp = vm.sp - numElements
err := vm.push(array)
if err != nil {
return err
}
}
}
return nil
}
func (vm *VM) buildArray(startIndex, endIndex int) object.Object {
elements := make([]object.Object, endIndex-startIndex)
for i := startIndex; i < endIndex; i++ {
elements[i-startIndex] = vm.stack[i]
}
return &object.Array{Elements: elements}
}
func isTruthy(obj object.Object) bool {
switch obj := obj.(type) {

View File

@@ -61,6 +61,24 @@ func testExpectedObject(t *testing.T, expected interface{}, actual object.Object
t.Errorf("testStringObject failed: %s", err)
}
case []int:
array, ok := actual.(*object.Array)
if !ok {
t.Errorf("object not Array: %T (%+v)", actual, actual)
}
if len(array.Elements) != len(expected) {
t.Errorf("wrong num of elements. want=%d, got=%d", len(expected), len(array.Elements))
return
}
for i, expectedElem := range expected {
err := testIntegerObject(int64(expectedElem), array.Elements[i])
if err != nil {
t.Errorf("testIntgerObject failed: %s", err)
}
}
case *object.Null:
if actual != Null {
t.Errorf("object is not Null: %T (%+v)", actual, actual)
@@ -204,3 +222,13 @@ func TestStringExpressions(t *testing.T) {
runVmTests(t, tests)
}
func TestArrayLiterals(t *testing.T) {
tests := []vmTestCase{
{"[]", []int{}},
{"[1, 2, 3]", []int{1, 2, 3}},
{"[1 + 2, 3 * 4, 5 + 6]", []int{3, 12, 11}},
}
runVmTests(t, tests)
}