type checking and error handling for builtins improved.
This commit is contained in:
@@ -1,27 +1,25 @@
|
||||
package builtins
|
||||
|
||||
import "monkey/object"
|
||||
|
||||
import (
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"monkey/object"
|
||||
"monkey/typing"
|
||||
)
|
||||
|
||||
// Read ...
|
||||
func Read(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(
|
||||
"read", args,
|
||||
typing.ExactArgs(1),
|
||||
typing.WithTypes(object.STRING_OBJ),
|
||||
); err != nil {
|
||||
return newError(err.Error())
|
||||
}
|
||||
|
||||
arg, ok := args[0].(*object.String)
|
||||
if !ok {
|
||||
return newError("argument to `read` expected to be `str` got=%T", args[0].Type())
|
||||
}
|
||||
|
||||
filename := arg.Value
|
||||
data, err := os.ReadFile(filename)
|
||||
filename := args[0].(*object.String).Value
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return newError("error reading file: %s", err)
|
||||
return newError("IOError: error reading from file %s: %s", filename, err)
|
||||
}
|
||||
|
||||
return &object.String{Value: string(data)}
|
||||
|
||||
Reference in New Issue
Block a user