-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.go
94 lines (80 loc) · 1.6 KB
/
repl.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
92
93
94
package repl
import (
"fmt"
"io"
"strings"
"github.com/dfirebaugh/punch/internal/emitters/wat"
"github.com/dfirebaugh/punch/internal/lexer"
"github.com/dfirebaugh/punch/internal/parser"
"github.com/chzyer/readline"
)
const PROMPT = ">> "
type REPL struct {
in io.Reader
out io.Writer
cmdHistory []string
}
func New(in io.Reader, out io.Writer) *REPL {
return &REPL{
in: in,
out: out,
}
}
func (repl *REPL) Start() {
rl, err := readline.New(PROMPT)
if err != nil {
panic(err)
}
defer rl.Close()
fmt.Println("type 'exit' to close")
for {
line, err := rl.Readline()
if err != nil {
if err == io.EOF {
break
}
fmt.Fprintln(repl.out, err)
continue
}
line = strings.TrimSpace(line)
repl.cmdHistory = append(repl.cmdHistory, line)
shouldContinue := repl.handleLine(line)
if !shouldContinue {
break
}
}
}
func (repl *REPL) handleLine(line string) bool {
line = strings.TrimSpace(line)
switch line {
case "history":
repl.showHistory()
case "clear":
repl.clearScreen()
case "exit":
return false
default:
fmt.Fprintf(repl.out, "Command entered: %s\n", line)
l := lexer.New("repl", line)
p := parser.New(l)
program := p.ParseProgram()
println("ast:")
json, err := program.JSONPretty()
if err != nil {
println(err.Error())
}
println(json)
println("")
println("wat:")
println(wat.GenerateWAT(program, true))
}
return true
}
func (repl *REPL) showHistory() {
for i, cmd := range repl.cmdHistory {
fmt.Fprintf(repl.out, "%d: %s\n", i+1, cmd)
}
}
func (repl *REPL) clearScreen() {
fmt.Fprint(repl.out, "\033[2J\033[H")
}