indexes
Some checks failed
Build / build (push) Failing after 5m57s
Test / build (push) Failing after 5m41s

This commit is contained in:
Chuck Smith
2024-02-27 16:45:22 -05:00
parent 0a1201f1bc
commit 4185926e3e
5 changed files with 116 additions and 0 deletions

View File

@@ -227,6 +227,19 @@ func (c *Compiler) Compile(node ast.Node) error {
c.emit(code.OpHash, len(node.Pairs)*2)
case *ast.IndexExpression:
err := c.Compile(node.Left)
if err != nil {
return err
}
err = c.Compile(node.Index)
if err != nil {
return err
}
c.emit(code.OpIndex)
}
return nil

View File

@@ -390,6 +390,42 @@ func TestHashLiterals(t *testing.T) {
runCompilerTests(t, tests)
}
func TestIndexExpressions(t *testing.T) {
tests := []compilerTestCase{
{
input: "[1, 2, 3][1 + 1]",
expectedConstants: []interface{}{1, 2, 3, 1, 1},
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.OpConstant, 3),
code.Make(code.OpConstant, 4),
code.Make(code.OpAdd),
code.Make(code.OpIndex),
code.Make(code.OpPop),
},
},
{
input: "{1: 2}[2 - 1]",
expectedConstants: []interface{}{1, 2, 2, 1},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpHash, 2),
code.Make(code.OpConstant, 2),
code.Make(code.OpConstant, 3),
code.Make(code.OpSub),
code.Make(code.OpIndex),
code.Make(code.OpPop),
},
},
}
runCompilerTests(t, tests)
}
func runCompilerTests(t *testing.T, tests []compilerTestCase) {
t.Helper()