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

@@ -194,6 +194,16 @@ func (c *Compiler) Compile(node ast.Node) error {
str := &object.String{Value: node.Value}
c.emit(code.OpConstant, c.addConstant(str))
case *ast.ArrayLiteral:
for _, el := range node.Elements {
err := c.Compile(el)
if err != nil {
return err
}
}
c.emit(code.OpArray, len(node.Elements))
}
return nil

View File

@@ -302,6 +302,49 @@ func TestStringExpressions(t *testing.T) {
runCompilerTests(t, tests)
}
func TestArrayLiterals(t *testing.T) {
tests := []compilerTestCase{
{
input: "[]",
expectedConstants: []interface{}{},
expectedInstructions: []code.Instructions{
code.Make(code.OpArray, 0),
code.Make(code.OpPop),
},
},
{
input: "[1, 2, 3]",
expectedConstants: []interface{}{1, 2, 3},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpConstant, 2),
code.Make(code.OpArray, 3),
code.Make(code.OpPop),
},
},
{
input: "[1 + 2, 3 - 4, 5 * 6]",
expectedConstants: []interface{}{1, 2, 3, 4, 5, 6},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpAdd),
code.Make(code.OpConstant, 2),
code.Make(code.OpConstant, 3),
code.Make(code.OpSub),
code.Make(code.OpConstant, 4),
code.Make(code.OpConstant, 5),
code.Make(code.OpMul),
code.Make(code.OpArray, 3),
code.Make(code.OpPop),
},
},
}
runCompilerTests(t, tests)
}
func runCompilerTests(t *testing.T, tests []compilerTestCase) {
t.Helper()