|
|
@@ -4,6 +4,7 @@ import (
|
|
|
"bytes"
|
|
|
"fmt"
|
|
|
"github/runnignwater/monkey/ast"
|
|
|
+ "hash/fnv"
|
|
|
"strings"
|
|
|
)
|
|
|
|
|
|
@@ -20,6 +21,7 @@ const (
|
|
|
StringObj = "STRING"
|
|
|
BuiltinObj = "BUILTIN"
|
|
|
ArrayObj = "ARRAY"
|
|
|
+ HashObj = "HASH"
|
|
|
)
|
|
|
|
|
|
// Object source code as an Object
|
|
|
@@ -30,6 +32,10 @@ type Object interface {
|
|
|
|
|
|
// BuiltinFunction 内建函数数据
|
|
|
type BuiltinFunction func(args ...Object) Object
|
|
|
+type HashKey struct {
|
|
|
+ Type ObjType
|
|
|
+ Value uint64
|
|
|
+}
|
|
|
|
|
|
type Integer struct {
|
|
|
Value int64
|
|
|
@@ -37,6 +43,9 @@ type Integer struct {
|
|
|
|
|
|
func (i *Integer) Type() ObjType { return IntegerObj }
|
|
|
func (i *Integer) Inspect() string { return fmt.Sprintf("%d", i.Value) }
|
|
|
+func (i *Integer) HashKey() HashKey {
|
|
|
+ return HashKey{Type: i.Type(), Value: uint64(i.Value)}
|
|
|
+}
|
|
|
|
|
|
type Boolean struct {
|
|
|
Value bool
|
|
|
@@ -44,6 +53,16 @@ type Boolean struct {
|
|
|
|
|
|
func (b *Boolean) Type() ObjType { return BooleanObj }
|
|
|
func (b *Boolean) Inspect() string { return fmt.Sprintf("%t", b.Value) }
|
|
|
+func (b *Boolean) HashKey() HashKey {
|
|
|
+ var value uint64
|
|
|
+
|
|
|
+ if b.Value {
|
|
|
+ value = 1
|
|
|
+ } else {
|
|
|
+ value = 0
|
|
|
+ }
|
|
|
+ return HashKey{Type: b.Type(), Value: value}
|
|
|
+}
|
|
|
|
|
|
type Null struct{}
|
|
|
|
|
|
@@ -95,6 +114,14 @@ type String struct {
|
|
|
|
|
|
func (s *String) Type() ObjType { return StringObj }
|
|
|
func (s *String) Inspect() string { return s.Value }
|
|
|
+func (s *String) HashKey() HashKey {
|
|
|
+ h := fnv.New64a()
|
|
|
+ _, err := h.Write([]byte(s.Value))
|
|
|
+ if err != nil {
|
|
|
+ return HashKey{Type: NullObj}
|
|
|
+ }
|
|
|
+ return HashKey{Type: s.Type(), Value: h.Sum64()}
|
|
|
+}
|
|
|
|
|
|
type Array struct {
|
|
|
Elements []Object
|
|
|
@@ -120,6 +147,35 @@ type Builtin struct {
|
|
|
Fn BuiltinFunction
|
|
|
}
|
|
|
|
|
|
-func (b Builtin) Type() ObjType { return BuiltinObj }
|
|
|
+func (b *Builtin) Type() ObjType { return BuiltinObj }
|
|
|
+
|
|
|
+func (b *Builtin) Inspect() string { return "builtin function" }
|
|
|
|
|
|
-func (b Builtin) Inspect() string { return "builtin function" }
|
|
|
+type HashPair struct {
|
|
|
+ Key Object
|
|
|
+ Value Object
|
|
|
+}
|
|
|
+type Hash struct {
|
|
|
+ Pairs map[HashKey]HashPair
|
|
|
+}
|
|
|
+
|
|
|
+func (h *Hash) Type() ObjType { return HashObj }
|
|
|
+func (h *Hash) Inspect() string {
|
|
|
+ var out bytes.Buffer
|
|
|
+
|
|
|
+ pairs := []string{}
|
|
|
+ for _, pair := range h.Pairs {
|
|
|
+ pairs = append(pairs, fmt.Sprintf("%s %s",
|
|
|
+ pair.Key.Inspect(), pair.Value.Inspect()))
|
|
|
+ }
|
|
|
+
|
|
|
+ out.WriteString("{")
|
|
|
+ out.WriteString(strings.Join(pairs, ", "))
|
|
|
+ out.WriteString("}")
|
|
|
+
|
|
|
+ return out.String()
|
|
|
+}
|
|
|
+
|
|
|
+type Hashtable interface {
|
|
|
+ HashKey() HashKey
|
|
|
+}
|