type checking and error handling for builtins improved.
This commit is contained in:
@@ -1,23 +1,21 @@
|
||||
package builtins
|
||||
|
||||
import "monkey/object"
|
||||
|
||||
import "unicode/utf8"
|
||||
import (
|
||||
"monkey/object"
|
||||
"monkey/typing"
|
||||
)
|
||||
|
||||
// Len ...
|
||||
func Len(args ...object.Object) object.Object {
|
||||
if len(args) != 1 {
|
||||
return newError("wrong number of arguments. got=%d, want=1",
|
||||
len(args))
|
||||
if err := typing.Check(
|
||||
"len", args,
|
||||
typing.ExactArgs(1),
|
||||
); err != nil {
|
||||
return newError(err.Error())
|
||||
}
|
||||
|
||||
switch arg := args[0].(type) {
|
||||
case *object.Array:
|
||||
return &object.Integer{Value: int64(len(arg.Elements))}
|
||||
case *object.String:
|
||||
return &object.Integer{Value: int64(utf8.RuneCountInString(arg.Value))}
|
||||
default:
|
||||
return newError("argument to `len` not supported, got %s",
|
||||
args[0].Type())
|
||||
if size, ok := args[0].(object.Sizeable); ok {
|
||||
return &object.Integer{Value: int64(size.Len())}
|
||||
}
|
||||
return newError("TypeError: object of type '%s' has no len()", args[0].Type())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user