/
evaluate.go
49 lines (40 loc) · 952 Bytes
/
evaluate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"io"
"os"
"github.com/kode4food/ale/data"
"github.com/kode4food/ale/eval"
"github.com/kode4food/ale/read"
)
// ErrFileNotFound is raised when a file is not found
const ErrFileNotFound = "file not found: %s"
// EvaluateStdIn reads from StdIn and evaluates it
func EvaluateStdIn() {
defer exitWithError()
buffer, _ := io.ReadAll(os.Stdin)
evalBuffer(buffer)
}
// EvaluateFile reads the specific source file and evaluates it
func EvaluateFile(filename string) {
defer exitWithError()
buffer, err := os.ReadFile(filename)
if err != nil {
fmt.Println(fmt.Errorf(ErrFileNotFound, filename))
os.Exit(-1)
}
evalBuffer(buffer)
}
func evalBuffer(src []byte) data.Value {
ns := makeUserNamespace()
r := read.FromString(data.String(src))
return eval.Block(ns, r)
}
func exitWithError() {
if rec := recover(); rec != nil {
if ev, ok := rec.(error); ok {
fmt.Println(ev.Error())
}
os.Exit(-2)
}
}