rearrange builtins
Some checks failed
Build / build (push) Successful in 10m31s
Test / build (push) Failing after 39m25s

This commit is contained in:
Chuck Smith
2024-03-24 14:00:22 -04:00
parent 387bb80094
commit b4ba660704
47 changed files with 652 additions and 515 deletions

51
object/array.go Normal file
View File

@@ -0,0 +1,51 @@
package object
import (
"bytes"
"strings"
)
// Array is the array literal type that holds a slice of Object(s)
type Array struct {
Elements []Object
}
func (ao *Array) Type() ObjectType {
return ARRAY_OBJ
}
func (ao *Array) Inspect() string {
var out bytes.Buffer
var elements []string
for _, e := range ao.Elements {
elements = append(elements, e.Inspect())
}
out.WriteString("[")
out.WriteString(strings.Join(elements, ", "))
out.WriteString("]")
return out.String()
}
func (ao *Array) String() string {
return ao.Inspect()
}
func (ao *Array) Equal(other Object) bool {
if obj, ok := other.(*Array); ok {
if len(ao.Elements) != len(obj.Elements) {
return false
}
for i, el := range ao.Elements {
cmp, ok := el.(Comparable)
if !ok {
return false
}
if !cmp.Equal(obj.Elements[i]) {
return false
}
}
return true
}
return false
}

28
object/bool.go Normal file
View File

@@ -0,0 +1,28 @@
package object
import (
"fmt"
)
type Boolean struct {
Value bool
}
func (b *Boolean) Type() ObjectType {
return BOOLEAN_OBJ
}
func (b *Boolean) Inspect() string {
return fmt.Sprintf("%t", b.Value)
}
func (b *Boolean) Clone() Object {
return &Boolean{Value: b.Value}
}
func (b *Boolean) String() string {
return b.Inspect()
}
func (b *Boolean) Equal(other Object) bool {
if obj, ok := other.(*Boolean); ok {
return b.Value == obj.Value
}
return false
}

18
object/builtin.go Normal file
View File

@@ -0,0 +1,18 @@
package object
import "fmt"
type Builtin struct {
Name string
Fn BuiltinFunction
}
func (b *Builtin) Type() ObjectType {
return BUILTIN_OBJ
}
func (b *Builtin) Inspect() string {
return fmt.Sprintf("<built-in function %s>", b.Name)
}
func (b *Builtin) String() string {
return b.Inspect()
}

View File

@@ -1,10 +0,0 @@
package object
// Args ...
func Args(args ...Object) Object {
elements := make([]Object, len(Arguments))
for i, arg := range Arguments {
elements[i] = &String{Value: arg}
}
return &Array{Elements: elements}
}

View File

@@ -1,29 +0,0 @@
package object
import (
"fmt"
"os"
)
// Assert ...
func Assert(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
}
if args[0].Type() != BOOLEAN_OBJ {
return newError("argument #1 to `assert` must be BOOLEAN, got %s",
args[0].Type())
}
if args[1].Type() != STRING_OBJ {
return newError("argument #2 to `assert` must be STRING, got %s",
args[0].Type())
}
if !args[0].(*Boolean).Value {
fmt.Printf("Assertion Error: %s", args[1].(*String).Value)
os.Exit(1)
}
return nil
}

View File

@@ -1,38 +0,0 @@
package object
// Bool ...
func Bool(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1", len(args))
}
switch arg := args[0].(type) {
case *Null:
return &Boolean{Value: false}
case *Boolean:
return arg
case *Integer:
if arg.Value == 0 {
return &Boolean{Value: false}
}
return &Boolean{Value: true}
case *String:
if len(arg.Value) > 0 {
return &Boolean{Value: true}
}
return &Boolean{Value: false}
case *Array:
if len(arg.Elements) > 0 {
return &Boolean{Value: true}
}
return &Boolean{Value: false}
case *Hash:
if len(arg.Pairs) > 0 {
return &Boolean{Value: true}
}
return &Boolean{Value: false}
default:
return newError("argument to `bool` not supported, got=%s", args[0].Type())
}
}

View File

@@ -1,17 +0,0 @@
package object
// Exit ...
func Exit(args ...Object) Object {
var status int
if len(args) == 1 {
if args[0].Type() != INTEGER_OBJ {
return newError("argument to `exit` must be INTEGER, got %s",
args[0].Type())
}
status = int(args[0].(*Integer).Value)
}
ExitFunction(status)
return nil
}

View File

@@ -1,34 +0,0 @@
package object
import (
"strings"
)
// Find ...
func Find(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
}
if haystack, ok := args[0].(*String); ok {
if needle, ok := args[1].(*String); ok {
index := strings.Index(haystack.Value, needle.Value)
return &Integer{Value: int64(index)}
} else {
return newError("expected arg #2 to be `str` got got=%T", args[1])
}
} else if haystack, ok := args[0].(*Array); ok {
needle := args[1]
index := -1
for i, el := range haystack.Elements {
if cmp, ok := el.(Comparable); ok && cmp.Equal(needle) {
index = i
break
}
}
return &Integer{Value: int64(index)}
} else {
return newError("expected arg #1 to be `str` or `array` got got=%T", args[0])
}
}

View File

@@ -1,20 +0,0 @@
package object
// First ...
func First(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if args[0].Type() != ARRAY_OBJ {
return newError("argument to `first` must be array, got %s",
args[0].Type())
}
arr := args[0].(*Array)
if len(arr.Elements) > 0 {
return arr.Elements[0]
}
return nil
}

View File

@@ -1,30 +0,0 @@
package object
import (
"bufio"
"fmt"
"io"
"os"
)
// Input ...
func Input(args ...Object) Object {
if len(args) > 0 {
obj, ok := args[0].(*String)
if !ok {
return newError(
"argument to `input` not supported, got %s",
args[0].Type(),
)
}
fmt.Fprintf(os.Stdout, obj.Value)
}
buffer := bufio.NewReader(os.Stdin)
line, _, err := buffer.ReadLine()
if err != nil && err != io.EOF {
return newError(fmt.Sprintf("error reading input from stdin: %s", err))
}
return &String{Value: string(line)}
}

View File

@@ -1,29 +0,0 @@
package object
import "strconv"
// Int ...
func Int(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1", len(args))
}
switch arg := args[0].(type) {
case *Boolean:
if arg.Value {
return &Integer{Value: 1}
}
return &Integer{Value: 0}
case *Integer:
return arg
case *String:
n, err := strconv.ParseInt(arg.Value, 10, 64)
if err != nil {
return newError("could not parse string to int: %s", err)
}
return &Integer{Value: n}
default:
return newError("argument to `int` not supported, got=%s", args[0].Type())
}
}

View File

@@ -1,27 +0,0 @@
package object
import (
"strings"
)
// Join ...
func Join(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if arr, ok := args[0].(*Array); ok {
if sep, ok := args[1].(*String); ok {
a := make([]string, len(arr.Elements))
for i, el := range arr.Elements {
a[i] = el.String()
}
return &String{Value: strings.Join(a, sep.Value)}
} else {
return newError("expected arg #2 to be `str` got got=%T", args[1])
}
} else {
return newError("expected arg #1 to be `array` got got=%T", args[0])
}
}

View File

@@ -1,21 +0,0 @@
package object
// Last ...
func Last(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if args[0].Type() != ARRAY_OBJ {
return newError("argument to `last` must be array, got %s",
args[0].Type())
}
arr := args[0].(*Array)
length := len(arr.Elements)
if length > 0 {
return arr.Elements[length-1]
}
return nil
}

View File

@@ -1,21 +0,0 @@
package object
import "unicode/utf8"
// Len ...
func Len(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
switch arg := args[0].(type) {
case *Array:
return &Integer{Value: int64(len(arg.Elements))}
case *String:
return &Integer{Value: int64(utf8.RuneCountInString(arg.Value))}
default:
return newError("argument to `len` not supported, got %s",
args[0].Type())
}
}

View File

@@ -1,16 +0,0 @@
package object
import "strings"
// Lower ...
func Lower(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if str, ok := args[0].(*String); ok {
return &String{Value: strings.ToLower(str.Value)}
}
return newError("expected `str` argument to `lower` got=%T", args[0])
}

View File

@@ -1,25 +0,0 @@
package object
// Pop ...
func Pop(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if args[0].Type() != ARRAY_OBJ {
return newError("argument to `pop` must be array, got %s",
args[0].Type())
}
arr := args[0].(*Array)
length := len(arr.Elements)
if length == 0 {
return newError("cannot pop from an empty array")
}
element := arr.Elements[length-1]
arr.Elements = arr.Elements[:length-1]
return element
}

View File

@@ -1,12 +0,0 @@
package object
import "fmt"
// Print ...
func Print(args ...Object) Object {
for _, arg := range args {
fmt.Println(arg.String())
}
return nil
}

View File

@@ -1,26 +0,0 @@
package object
// Push ...
func Push(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
}
if args[0].Type() != ARRAY_OBJ {
return newError("argument to `push` must be array, got %s",
args[0].Type())
}
arr := args[0].(*Array)
length := len(arr.Elements)
newElements := make([]Object, length+1)
copy(newElements, arr.Elements)
if immutable, ok := args[1].(Immutable); ok {
newElements[length] = immutable.Clone()
} else {
newElements[length] = args[1]
}
return &Array{Elements: newElements}
}

View File

@@ -1,26 +0,0 @@
package object
import (
"os"
)
// Read ...
func Read(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
arg, ok := args[0].(*String)
if !ok {
return newError("argument to `read` expected to be `str` got=%T", args[0].Type())
}
filename := arg.Value
data, err := os.ReadFile(filename)
if err != nil {
return newError("error reading file: %s", err)
}
return &String{Value: string(data)}
}

View File

@@ -1,23 +0,0 @@
package object
// Rest ...
func Rest(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if args[0].Type() != ARRAY_OBJ {
return newError("argument to `rest` must be array, got %s",
args[0].Type())
}
arr := args[0].(*Array)
length := len(arr.Elements)
if length > 0 {
newElements := make([]Object, length-1, length-1)
copy(newElements, arr.Elements[1:length])
return &Array{Elements: newElements}
}
return nil
}

View File

@@ -1,36 +0,0 @@
package object
import (
"strings"
)
// Split ...
func Split(args ...Object) Object {
if len(args) < 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if obj, ok := args[0].(*String); ok {
var sep string
s := obj.Value
if len(args) == 2 {
if obj, ok := args[1].(*String); ok {
sep = obj.Value
} else {
return newError("expected arg #2 to be `str` got=%T", args[1])
}
}
tokens := strings.Split(s, sep)
elements := make([]Object, len(tokens))
for i, token := range tokens {
elements[i] = &String{Value: token}
}
return &Array{Elements: elements}
} else {
return newError("expected arg #1 to be `str` got got=%T", args[0])
}
}

View File

@@ -1,19 +0,0 @@
package object
import (
"fmt"
)
// Str ...
func Str(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1", len(args))
}
arg, ok := args[0].(fmt.Stringer)
if !ok {
return newError("argument to `str` not supported, got %s", args[0].Type())
}
return &String{Value: arg.String()}
}

View File

@@ -1,10 +0,0 @@
package object
// TypeOf ...
func TypeOf(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1", len(args))
}
return &String{Value: string(args[0].Type())}
}

View File

@@ -1,16 +0,0 @@
package object
import "strings"
// Upper ...
func Upper(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
if str, ok := args[0].(*String); ok {
return &String{Value: strings.ToUpper(str.Value)}
}
return newError("expected `str` argument to `upper` got=%T", args[0])
}

View File

@@ -1,32 +0,0 @@
package object
import (
"os"
)
// Write ...
func Write(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
}
arg, ok := args[0].(*String)
if !ok {
return newError("argument #1 to `write` expected to be `str` got=%T", args[0].Type())
}
filename := arg.Value
arg, ok = args[1].(*String)
if !ok {
return newError("argument #2 to `write` expected to be `str` got=%T", args[1].Type())
}
data := []byte(arg.Value)
err := os.WriteFile(filename, data, 0755)
if err != nil {
return newError("error writing file: %s", err)
}
return &Null{}
}

View File

@@ -1,51 +0,0 @@
package object
import (
"fmt"
"sort"
)
// Builtins ...
var Builtins = map[string]*Builtin{
"len": {Name: "len", Fn: Len},
"input": {Name: "input", Fn: Input},
"print": {Name: "print", Fn: Print},
"first": {Name: "first", Fn: First},
"last": {Name: "last", Fn: Last},
"rest": {Name: "rest", Fn: Rest},
"push": {Name: "push", Fn: Push},
"pop": {Name: "pop", Fn: Pop},
"exit": {Name: "exit", Fn: Exit},
"assert": {Name: "assert", Fn: Assert},
"bool": {Name: "bool", Fn: Bool},
"int": {Name: "int", Fn: Int},
"str": {Name: "str", Fn: Str},
"typeof": {Name: "typeof", Fn: TypeOf},
"args": {Name: "args", Fn: Args},
"lower": {Name: "lower", Fn: Lower},
"upper": {Name: "upper", Fn: Upper},
"join": {Name: "join", Fn: Join},
"split": {Name: "split", Fn: Split},
"find": {Name: "find", Fn: Find},
"read": {Name: "read", Fn: Read},
"write": {Name: "write", Fn: Write},
}
// BuiltinsIndex ...
var BuiltinsIndex []*Builtin
func init() {
var keys []string
for k := range Builtins {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
BuiltinsIndex = append(BuiltinsIndex, Builtins[k])
}
}
func newError(format string, a ...interface{}) *Error {
return &Error{Message: fmt.Sprintf(format, a...)}
}

37
object/closure.go Normal file
View File

@@ -0,0 +1,37 @@
package object
import (
"fmt"
"monkey/code"
)
type CompiledFunction struct {
Instructions code.Instructions
NumLocals int
NumParameters int
}
func (cf *CompiledFunction) Type() ObjectType {
return COMPILED_FUNCTION_OBJ
}
func (cf *CompiledFunction) Inspect() string {
return fmt.Sprintf("CompiledFunction[%p]", cf)
}
func (cf *CompiledFunction) String() string {
return cf.Inspect()
}
type Closure struct {
Fn *CompiledFunction
Free []Object
}
func (c *Closure) Type() ObjectType {
return CLOSURE_OBJ
}
func (c *Closure) Inspect() string {
return fmt.Sprintf("Closure[%p]", c)
}
func (c *Closure) String() string {
return c.Inspect()
}

18
object/error.go Normal file
View File

@@ -0,0 +1,18 @@
package object
type Error struct {
Message string
}
func (e *Error) Type() ObjectType {
return ERROR_OBJ
}
func (e *Error) Inspect() string {
return "Error: " + e.Message
}
func (e *Error) Clone() Object {
return &Error{Message: e.Message}
}
func (e *Error) String() string {
return e.Message
}

51
object/function.go Normal file
View File

@@ -0,0 +1,51 @@
package object
import (
"bytes"
"monkey/ast"
"strings"
)
type Function struct {
Parameters []*ast.Identifier
Body *ast.BlockStatement
Env *Environment
}
func (f *Function) Type() ObjectType {
return FUNCTION_OBJ
}
func (f *Function) Inspect() string {
var out bytes.Buffer
params := []string{}
for _, p := range f.Parameters {
params = append(params, p.String())
}
out.WriteString("fn")
out.WriteString("(")
out.WriteString(strings.Join(params, ", "))
out.WriteString(") {\n")
out.WriteString(f.Body.String())
out.WriteString("\n}")
return out.String()
}
func (f *Function) String() string {
return f.Inspect()
}
type ReturnValue struct {
Value Object
}
func (rv *ReturnValue) Type() ObjectType {
return RETURN_VALUE_OBJ
}
func (rv *ReturnValue) Inspect() string {
return rv.Value.Inspect()
}
func (rv *ReturnValue) String() string {
return rv.Inspect()
}

91
object/hash.go Normal file
View File

@@ -0,0 +1,91 @@
package object
import (
"bytes"
"fmt"
"hash/fnv"
"strings"
)
type HashKey struct {
Type ObjectType
Value uint64
}
func (b *Boolean) HashKey() HashKey {
var value uint64
if b.Value {
value = 1
} else {
value = 0
}
return HashKey{Type: b.Type(), Value: value}
}
func (i *Integer) HashKey() HashKey {
return HashKey{Type: i.Type(), Value: uint64(i.Value)}
}
func (s *String) HashKey() HashKey {
h := fnv.New64a()
h.Write([]byte(s.Value))
return HashKey{Type: s.Type(), Value: h.Sum64()}
}
type HashPair struct {
Key Object
Value Object
}
type Hash struct {
Pairs map[HashKey]HashPair
}
func (h *Hash) Type() ObjectType {
return HASH_OBJ
}
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()
}
func (h *Hash) String() string {
return h.Inspect()
}
func (h *Hash) Equal(other Object) bool {
if obj, ok := other.(*Hash); ok {
if len(h.Pairs) != len(obj.Pairs) {
return false
}
for _, pair := range h.Pairs {
left := pair.Value
hashed := left.(Hashable)
right, ok := obj.Pairs[hashed.HashKey()]
if !ok {
return false
}
cmp, ok := left.(Comparable)
if !ok {
return false
}
if !cmp.Equal(right.Value) {
return false
}
}
return true
}
return false
}

26
object/int.go Normal file
View File

@@ -0,0 +1,26 @@
package object
import "fmt"
type Integer struct {
Value int64
}
func (i *Integer) Type() ObjectType {
return INTEGER_OBJ
}
func (i *Integer) Inspect() string {
return fmt.Sprintf("%d", i.Value)
}
func (i *Integer) Clone() Object {
return &Integer{Value: i.Value}
}
func (i *Integer) String() string {
return i.Inspect()
}
func (i *Integer) Equal(other Object) bool {
if obj, ok := other.(*Integer); ok {
return i.Value == obj.Value
}
return false
}

17
object/null.go Normal file
View File

@@ -0,0 +1,17 @@
package object
type Null struct{}
func (n *Null) Type() ObjectType {
return NULL_OBJ
}
func (n *Null) Inspect() string {
return "null"
}
func (n *Null) String() string {
return n.Inspect()
}
func (n *Null) Equal(other Object) bool {
_, ok := other.(*Null)
return ok
}

View File

@@ -1,14 +1,6 @@
package object
import (
"bytes"
"fmt"
"hash/fnv"
"monkey/ast"
"monkey/code"
"strings"
)
// Type represents the type of an object
type ObjectType string
const (
@@ -39,333 +31,19 @@ type Immutable interface {
Clone() Object
}
// Object represents a value and implementations are expected to implement
// `Type()` and `Inspect()` functions
type Object interface {
Type() ObjectType
String() string
Inspect() string
}
type Integer struct {
Value int64
}
type CompiledFunction struct {
Instructions code.Instructions
NumLocals int
NumParameters int
}
func (i *Integer) Type() ObjectType {
return INTEGER_OBJ
}
func (i *Integer) Inspect() string {
return fmt.Sprintf("%d", i.Value)
}
func (i *Integer) Clone() Object {
return &Integer{Value: i.Value}
}
func (i *Integer) String() string {
return i.Inspect()
}
func (i *Integer) Equal(other Object) bool {
if obj, ok := other.(*Integer); ok {
return i.Value == obj.Value
}
return false
}
type Boolean struct {
Value bool
}
func (b *Boolean) Type() ObjectType {
return BOOLEAN_OBJ
}
func (b *Boolean) Inspect() string {
return fmt.Sprintf("%t", b.Value)
}
func (b *Boolean) Clone() Object {
return &Boolean{Value: b.Value}
}
func (b *Boolean) String() string {
return b.Inspect()
}
func (b *Boolean) Equal(other Object) bool {
if obj, ok := other.(*Boolean); ok {
return b.Value == obj.Value
}
return false
}
type Null struct{}
func (n *Null) Type() ObjectType {
return NULL_OBJ
}
func (n *Null) Inspect() string {
return "null"
}
func (n *Null) String() string {
return n.Inspect()
}
func (n *Null) Equal(other Object) bool {
_, ok := other.(*Null)
return ok
}
type ReturnValue struct {
Value Object
}
func (rv *ReturnValue) Type() ObjectType {
return RETURN_VALUE_OBJ
}
func (rv *ReturnValue) Inspect() string {
return rv.Value.Inspect()
}
func (rv *ReturnValue) String() string {
return rv.Inspect()
}
type Error struct {
Message string
}
func (e *Error) Type() ObjectType {
return ERROR_OBJ
}
func (e *Error) Inspect() string {
return "Error: " + e.Message
}
func (e *Error) Clone() Object {
return &Error{Message: e.Message}
}
func (e *Error) String() string {
return e.Message
}
type Function struct {
Parameters []*ast.Identifier
Body *ast.BlockStatement
Env *Environment
}
func (f *Function) Type() ObjectType {
return FUNCTION_OBJ
}
func (f *Function) Inspect() string {
var out bytes.Buffer
params := []string{}
for _, p := range f.Parameters {
params = append(params, p.String())
}
out.WriteString("fn")
out.WriteString("(")
out.WriteString(strings.Join(params, ", "))
out.WriteString(") {\n")
out.WriteString(f.Body.String())
out.WriteString("\n}")
return out.String()
}
func (f *Function) String() string {
return f.Inspect()
}
type String struct {
Value string
}
func (s *String) Type() ObjectType {
return STRING_OBJ
}
func (s *String) Inspect() string {
return fmt.Sprintf("%#v", s.Value)
}
func (s *String) Clone() Object {
return &String{Value: s.Value}
}
func (s *String) String() string {
return s.Value
}
func (s *String) Equal(other Object) bool {
if obj, ok := other.(*String); ok {
return s.Value == obj.Value
}
return false
}
type BuiltinFunction func(args ...Object) Object
type Builtin struct {
Name string
Fn BuiltinFunction
}
func (b *Builtin) Type() ObjectType {
return BUILTIN_OBJ
}
func (b *Builtin) Inspect() string {
return fmt.Sprintf("<built-in function %s>", b.Name)
}
func (b *Builtin) String() string {
return b.Inspect()
}
type Array struct {
Elements []Object
}
func (ao *Array) Type() ObjectType {
return ARRAY_OBJ
}
func (ao *Array) Inspect() string {
var out bytes.Buffer
elements := []string{}
for _, e := range ao.Elements {
elements = append(elements, e.Inspect())
}
out.WriteString("[")
out.WriteString(strings.Join(elements, ", "))
out.WriteString("]")
return out.String()
}
func (ao *Array) String() string {
return ao.Inspect()
}
func (ao *Array) Equal(other Object) bool {
if obj, ok := other.(*Array); ok {
if len(ao.Elements) != len(obj.Elements) {
return false
}
for i, el := range ao.Elements {
cmp, ok := el.(Comparable)
if !ok {
return false
}
if !cmp.Equal(obj.Elements[i]) {
return false
}
}
return true
}
return false
}
type HashKey struct {
Type ObjectType
Value uint64
}
func (b *Boolean) HashKey() HashKey {
var value uint64
if b.Value {
value = 1
} else {
value = 0
}
return HashKey{Type: b.Type(), Value: value}
}
// Hashable is the interface for all hashable objects which must implement
// the HashKey() method which returns a HashKey result.
type Hashable interface {
HashKey() HashKey
}
func (i *Integer) HashKey() HashKey {
return HashKey{Type: i.Type(), Value: uint64(i.Value)}
}
func (s *String) HashKey() HashKey {
h := fnv.New64a()
h.Write([]byte(s.Value))
return HashKey{Type: s.Type(), Value: h.Sum64()}
}
type HashPair struct {
Key Object
Value Object
}
type Hash struct {
Pairs map[HashKey]HashPair
}
func (h *Hash) Type() ObjectType {
return HASH_OBJ
}
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()
}
func (h *Hash) String() string {
return h.Inspect()
}
func (h *Hash) Equal(other Object) bool {
if obj, ok := other.(*Hash); ok {
if len(h.Pairs) != len(obj.Pairs) {
return false
}
for _, pair := range h.Pairs {
left := pair.Value
hashed := left.(Hashable)
right, ok := obj.Pairs[hashed.HashKey()]
if !ok {
return false
}
cmp, ok := left.(Comparable)
if !ok {
return false
}
if !cmp.Equal(right.Value) {
return false
}
}
return true
}
return false
}
func (cf *CompiledFunction) Type() ObjectType {
return COMPILED_FUNCTION_OBJ
}
func (cf *CompiledFunction) Inspect() string {
return fmt.Sprintf("CompiledFunction[%p]", cf)
}
func (cf *CompiledFunction) String() string {
return cf.Inspect()
}
type Closure struct {
Fn *CompiledFunction
Free []Object
}
func (c *Closure) Type() ObjectType {
return CLOSURE_OBJ
}
func (c *Closure) Inspect() string {
return fmt.Sprintf("Closure[%p]", c)
}
func (c *Closure) String() string {
return c.Inspect()
}
// BuiltinFunction represents the builtin function type
type BuiltinFunction func(args ...Object) Object

26
object/str.go Normal file
View File

@@ -0,0 +1,26 @@
package object
import "fmt"
type String struct {
Value string
}
func (s *String) Type() ObjectType {
return STRING_OBJ
}
func (s *String) Inspect() string {
return fmt.Sprintf("%#v", s.Value)
}
func (s *String) Clone() Object {
return &String{Value: s.Value}
}
func (s *String) String() string {
return s.Value
}
func (s *String) Equal(other Object) bool {
if obj, ok := other.(*String); ok {
return s.Value == obj.Value
}
return false
}