type checking and error handling for builtins improved.
Some checks failed
Build / build (push) Successful in 11m16s
Test / build (push) Failing after 17m0s

This commit is contained in:
Chuck Smith
2024-03-25 16:18:08 -04:00
parent 1c99d2198b
commit 6d234099d1
52 changed files with 650 additions and 433 deletions

View File

@@ -2,6 +2,7 @@ package builtins
import (
"monkey/object"
"monkey/typing"
"sort"
)
@@ -11,19 +12,29 @@ import (
// Find ...
func Find(args ...object.Object) object.Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
if err := typing.Check(
"find", args,
typing.ExactArgs(2),
); err != nil {
return newError(err.Error())
}
// find substring in string
if haystack, ok := args[0].(*object.String); ok {
if needle, ok := args[1].(*object.String); ok {
index := strings.Index(haystack.Value, needle.Value)
return &object.Integer{Value: int64(index)}
} else {
return newError("expected arg #2 to be `str` got got=%T", args[1])
if err := typing.Check(
"find", args,
typing.WithTypes(object.STRING_OBJ, object.STRING_OBJ),
); err != nil {
return newError(err.Error())
}
} else if haystack, ok := args[0].(*object.Array); ok {
needle := args[1].(*object.String)
index := strings.Index(haystack.Value, needle.Value)
return &object.Integer{Value: int64(index)}
}
// find in array
if haystack, ok := args[0].(*object.Array); ok {
needle := args[1].(object.Comparable)
i := sort.Search(len(haystack.Elements), func(i int) bool {
return needle.Compare(haystack.Elements[i]) == 0
@@ -32,7 +43,10 @@ func Find(args ...object.Object) object.Object {
return &object.Integer{Value: int64(i)}
}
return &object.Integer{Value: -1}
} else {
return newError("expected arg #1 to be `str` or `array` got got=%T", args[0])
}
return newError(
"TypeError: find() expected argument #1 to be `array` or `str` got `%s`",
args[0].Type(),
)
}