-
Notifications
You must be signed in to change notification settings - Fork 1
/
gosick.go
91 lines (79 loc) · 2.01 KB
/
gosick.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"github.com/GeertJohan/go.linenoise"
"github.com/jessevdk/go-flags"
"github.com/k0kubun/gosick/scheme"
"io/ioutil"
"log"
"strings"
)
type Options struct {
Expression []string `short:"e" long:"expression" description:"excecute given expression"`
DumpAST bool `short:"a" long:"ast" default:"false" description:"whether leaf nodes are plotted"`
}
func main() {
options := new(Options)
args, err := flags.Parse(options)
if err != nil {
return
}
if len(args) > 0 {
executeSourceCode(args[0], options)
} else if len(options.Expression) > 0 {
executeExpression(strings.Join(options.Expression, " "), options.DumpAST)
} else {
invokeInteractiveShell(options)
}
}
func executeSourceCode(filename string, options *Options) {
buffer, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
executeExpression(string(buffer), options.DumpAST)
}
func executeExpression(expression string, dumpAST bool) {
interpreter := scheme.NewInterpreter(expression)
interpreter.PrintErrors(dumpAST)
}
func invokeInteractiveShell(options *Options) {
mainInterpreter := scheme.NewInterpreter("")
for {
indentLevel := 0
expression := ""
for {
currentLine, err := linenoise.Line(shellPrompt(indentLevel))
if err != nil {
log.Fatal(err)
return
}
if currentLine == "exit" {
return
}
linenoise.AddHistory(currentLine)
expression += " "
expression += currentLine
interpreter := scheme.NewInterpreter(expression)
indentLevel = interpreter.IndentLevel()
if indentLevel == 0 {
mainInterpreter.ReloadSourceCode(expression)
mainInterpreter.PrintResults(options.DumpAST)
break
} else if indentLevel < 0 {
fmt.Println("*** ERROR: extra close parentheses")
expression = ""
indentLevel = 0
}
}
}
}
func shellPrompt(indentLevel int) string {
if indentLevel == 0 {
return "gosick> "
} else if indentLevel > 0 {
return fmt.Sprintf("gosick* %s", strings.Repeat(" ", indentLevel))
} else {
panic("Negative indent level")
}
}