indexes
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user