hash
Some checks failed
Build / build (push) Failing after 1m13s
Test / build (push) Failing after 2m1s

This commit is contained in:
Chuck Smith
2024-02-26 16:59:37 -05:00
parent 8721665bc1
commit 0a1201f1bc
5 changed files with 152 additions and 0 deletions

View File

@@ -5,6 +5,7 @@ import (
"monkey/ast"
"monkey/code"
"monkey/object"
"sort"
)
type EmittedInstruction struct {
@@ -204,6 +205,28 @@ func (c *Compiler) Compile(node ast.Node) error {
c.emit(code.OpArray, len(node.Elements))
case *ast.HashLiteral:
keys := []ast.Expression{}
for k := range node.Pairs {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].String() < keys[j].String()
})
for _, k := range keys {
err := c.Compile(k)
if err != nil {
return err
}
err = c.Compile(node.Pairs[k])
if err != nil {
return err
}
}
c.emit(code.OpHash, len(node.Pairs)*2)
}
return nil