Eval complete

This commit is contained in:
Chuck Smith
2024-01-20 11:16:56 -05:00
parent 581573486c
commit 10821fc88a
4 changed files with 183 additions and 4 deletions

View File

@@ -1,16 +1,26 @@
package object
func NewEnclosedEnvironment(outer *Environment) *Environment {
env := NewEnvironment()
env.outer = outer
return env
}
func NewEnvironment() *Environment {
s := make(map[string]Object)
return &Environment{store: s}
return &Environment{store: s, outer: nil}
}
type Environment struct {
store map[string]Object
outer *Environment
}
func (e *Environment) Get(name string) (Object, bool) {
obj, ok := e.store[name]
if !ok && e.outer != nil {
obj, ok = e.outer.Get(name)
}
return obj, ok
}

View File

@@ -1,6 +1,11 @@
package object
import "fmt"
import (
"bytes"
"fmt"
"monkey/ast"
"strings"
)
type ObjectType string
@@ -10,6 +15,7 @@ const (
NULL_OBJ = "NULL"
RETURN_VALUE_OBJ = "RETURN_VALUE"
ERROR_OBJ = "ERROR"
FUNCTION_OBJ = "FUNCTION"
)
type Object interface {
@@ -72,3 +78,31 @@ func (e *Error) Type() ObjectType {
func (e *Error) Inspect() string {
return "Error: " + 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()
}