Extra Features
Some checks failed
Build / build (push) Failing after 1m40s
Test / build (push) Failing after 11m47s

This commit is contained in:
Chuck Smith
2024-03-14 21:25:47 -04:00
parent 36f04713bd
commit 997f0865f4
20 changed files with 757 additions and 128 deletions

View File

@@ -1,6 +1,12 @@
package object
import "fmt"
import (
"bufio"
"fmt"
"io"
"os"
"unicode/utf8"
)
var Builtins = []struct {
Name string
@@ -18,7 +24,7 @@ var Builtins = []struct {
case *Array:
return &Integer{Value: int64(len(arg.Elements))}
case *String:
return &Integer{Value: int64(len(arg.Value))}
return &Integer{Value: int64(utf8.RuneCountInString(arg.Value))}
default:
return newError("argument to `len` not supported, got %s",
args[0].Type())
@@ -27,7 +33,30 @@ var Builtins = []struct {
},
},
{
"puts",
"input",
&Builtin{Fn: func(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)}
}},
},
{
"print",
&Builtin{Fn: func(args ...Object) Object {
for _, arg := range args {
fmt.Println(arg.Inspect())
@@ -123,6 +152,48 @@ var Builtins = []struct {
},
},
},
{
"pop",
&Builtin{Fn: func(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
},
},
},
{
"exit",
&Builtin{Fn: func(args ...Object) Object {
if len(args) == 1 {
if args[0].Type() != INTEGER_OBJ {
return newError("argument to `exit` must be INTEGER, got %s",
args[0].Type())
}
os.Exit(int(args[0].(*Integer).Value))
} else {
os.Exit(0)
}
return nil
},
},
},
}
func newError(format string, a ...interface{}) *Error {