Skip to content

Commit

Permalink
len buiiltin function!!
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonak-Adipta-Kalita committed Apr 9, 2023
1 parent 6b84f18 commit 541e759
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 9 deletions.
21 changes: 21 additions & 0 deletions evaluator/builtins.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package evaluator

import "github.com/Jonak-Adipta-Kalita/JAK-Programming-Language/object"

var builtins = map[string]*object.Builtin{
"len": &object.Builtin{
Fn: func(args ...object.Object) object.Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
switch arg := args[0].(type) {
case *object.String:
return &object.Integer{Value: int64(len(arg.Value))}
default:
return newError("argument to `len` not supported, got %s",
args[0].Type())
}
},
},
}
25 changes: 16 additions & 9 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,15 @@ func evalIdentifier(
node *ast.Identifier,
env *object.Environment,
) object.Object {
val, ok := env.Get(node.Value)
if !ok {
return newError("identifier not found: " + node.Value)
if val, ok := env.Get(node.Value); ok {
return val
}
return val

if builtin, ok := builtins[node.Value]; ok {
return builtin
}

return newError("identifier not found: " + node.Value)
}

func evalProgram(program *ast.Program, env *object.Environment) object.Object {
Expand Down Expand Up @@ -278,13 +282,16 @@ func isError(obj object.Object) bool {
}

func applyFunction(fn object.Object, args []object.Object) object.Object {
function, ok := fn.(*object.Function)
if !ok {
switch fn := fn.(type) {
case *object.Function:
extendedEnv := extendFunctionEnv(fn, args)
evaluated := Eval(fn.Body, extendedEnv)
return unwrapReturnValue(evaluated)
case *object.Builtin:
return fn.Fn(args...)
default:
return newError("not a function: %s", fn.Type())
}
extendedEnv := extendFunctionEnv(function, args)
evaluated := Eval(function.Body, extendedEnv)
return unwrapReturnValue(evaluated)
}

func extendFunctionEnv(
Expand Down
11 changes: 11 additions & 0 deletions object/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const (

RETURN_VALUE_OBJ = "RETURN_VALUE"
FUNCTION_OBJ = "FUNCTION"

BUILTIN_OBJ = "BUILTIN"
)

type Boolean struct {
Expand Down Expand Up @@ -88,3 +90,12 @@ type String struct {

func (s *String) Type() ObjectType { return STRING_OBJ }
func (s *String) Inspect() string { return s.Value }

type BuiltinFunction func(args ...Object) Object

type Builtin struct {
Fn BuiltinFunction
}

func (b *Builtin) Type() ObjectType { return BUILTIN_OBJ }
func (b *Builtin) Inspect() string { return "builtin function" }

0 comments on commit 541e759

Please sign in to comment.