forked from janne/go-lisp
/
go-lisp.go
67 lines (63 loc) · 1.43 KB
/
go-lisp.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"bufio"
"flag"
"fmt"
"github.com/janne/go-lisp/lisp"
"io/ioutil"
"os"
"strings"
)
func main() {
var file = flag.String("file", "", "File to interpret")
var repl = flag.Bool("i", false, "Interactive mode")
flag.Parse()
if *repl {
Repl()
} else if *file != "" {
if output, err := ioutil.ReadFile(*file); err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
if _, err := lisp.EvalString(string(output)); err != nil {
fmt.Printf("ERROR: %v\n", err)
}
}
} else {
if output, err := ioutil.ReadAll(bufio.NewReader(os.Stdin)); err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
lisp.EvalString(string(output))
}
}
}
func Repl() {
fmt.Printf("Welcome to the Lisp REPL\n")
reader := bufio.NewReader(os.Stdin)
expr := ""
for {
if expr == "" {
fmt.Printf("\n> ")
}
line, _ := reader.ReadString('\n')
expr = fmt.Sprintf("%v%v", expr, line)
openCount := strings.Count(expr, "(")
closeCount := strings.Count(expr, ")")
if openCount < closeCount {
fmt.Printf("ERROR: Malformed expression: %v", line)
expr = ""
} else if openCount == closeCount {
if strings.TrimSpace(expr) != "" {
if response, err := lisp.EvalString(expr); err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
if response == lisp.Nil {
fmt.Println(";Unspecified return value")
} else {
fmt.Printf(";Value: %v\n", response.Inspect())
}
}
}
expr = ""
}
}
}