Skip to content

Commit

Permalink
props: add Kernel#read
Browse files Browse the repository at this point in the history
  • Loading branch information
Syuparn committed Dec 30, 2023
1 parent 8acc39b commit 67e88de
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
30 changes: 30 additions & 0 deletions evaluator/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10379,6 +10379,36 @@ func TestEvalAssertRaises(t *testing.T) {
}
}

func TestEvalRead(t *testing.T) {
tests := []struct {
input string
expected object.PanObject
}{
{
`read("testdata/sample.txt")`,
object.NewPanStr("dummy\n"),
},
{
`read()`,
object.NewTypeErr("read requires at least 1 arg"),
},
{
`read(1)`,
object.NewTypeErr("1 cannot be treated as str"),
},
{
`read("testdata/notfound.txt")`,
object.NewFileNotFoundErr(`"testdata/notfound.txt" cannot be opened: open testdata/notfound.txt: no such file or directory`),
},
// TODO: add non-text options
}

for _, tt := range tests {
actual := testEval(t, tt.input)
testValue(t, actual, tt.expected)
}
}

func TestEvalTry(t *testing.T) {
tests := []struct {
input string
Expand Down
1 change: 1 addition & 0 deletions evaluator/testdata/sample.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dummy
33 changes: 33 additions & 0 deletions props/kernel_props.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package props
import (
"fmt"
"os"
"path/filepath"

"github.com/Syuparn/pangaea/object"
)
Expand Down Expand Up @@ -123,5 +124,37 @@ func KernelProps(propContainer map[string]object.PanObject) map[string]object.Pa
),
"import": propContainer["Kernel_import"],
"invite!": propContainer["Kernel_invite!"],
"read": f(
func(
env *object.Env, kwargs *object.PanObj, args ...object.PanObject,
) object.PanObject {
if len(args) < 1 {
return object.NewTypeErr("read requires at least 1 arg")
}

pathObj, ok := object.TraceProtoOfStr(args[0])
if !ok {
return object.NewTypeErr(
fmt.Sprintf("%s cannot be treated as str", args[0].Repr()))
}

filePath := pathObj.Value
// HACK: find relative file path
if p, ok := env.Get(object.GetSymHash(object.SourcePathVar)); ok {
if p.Type() != object.StrType {
return object.NewTypeErr(fmt.Sprintf("%s %s must be str", object.SourcePathVar, p.Inspect()))
}
filePath = filepath.Join(filepath.Dir(filePath), filePath)
}

b, err := os.ReadFile(filePath)
if err != nil {
return object.NewFileNotFoundErr(
fmt.Sprintf("%s cannot be opened: %s", args[0].Repr(), err.Error()))
}

return object.NewPanStr(string(b))
},
),
}
}

0 comments on commit 67e88de

Please sign in to comment.