-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.go
222 lines (185 loc) · 4.98 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (c) 2020 Brandon Buck
package luna
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/chzyer/readline"
glua "github.com/yuin/gopher-lua"
"github.com/yuin/gopher-lua/parse"
)
var errExit = errors.New("Exit")
// REPL represent a Read-Eval-Print-Loop
type REPL struct {
lineNumber uint
promptNumFmt string
promptStrFmt string
historyPath string
engine *Engine
input *readline.Instance
}
const defaultPrompt = "{name} ({n})"
// REPLConfig provides a mean for configuring a lua.REPL value.
// -- HistoryFilePath is the path to the history file for storing the written
// history of the REPL session (optional)
// -- Prompt is a fmt string to print as the prompt for each REPL input line.
// There is a special format value {n} here where you want the line number
// to go, or {name} as a place to inject the name provided (if any).
// -- Name is a name given, really only useful when no prompt is given as this
// value is injected into the prompt.
type REPLConfig struct {
Engine *Engine
HistoryFilePath string
Name string
Prompt string
}
// NewREPL creates a REPL struct and seeds it with the necessary values to
// prepare it for use. Uses the default .repl-history file.
func NewREPL(eng *Engine, name string) *REPL {
return NewREPLWithConfig(REPLConfig{
Prompt: defaultPrompt,
Engine: eng,
Name: name,
})
}
// NewREPLWithConfig creates a REPL from the provided configuration.
func NewREPLWithConfig(config REPLConfig) *REPL {
prompt := defaultPrompt
if len(config.Prompt) > 0 {
prompt = config.Prompt
}
prompt = strings.Replace(prompt, "{name}", config.Name, -1)
repl := &REPL{
promptNumFmt: strings.Replace(prompt, "{n}", "%[1]d", -1),
promptStrFmt: strings.Replace(prompt, "{n}", "%[1]s", -1),
engine: config.Engine,
}
if len(config.HistoryFilePath) == 0 {
repl.historyPath = config.HistoryFilePath
}
repl.engine.SetGlobal("inspect", func(eng *Engine) int {
val := eng.PopValue()
eng.PushValue(val.Inspect(""))
return 1
})
return repl
}
// Run begins the execution fo the read-eval-print-loop. Executing the REPL
// only ends when an input line matches `.exit` or if an error is encountered.
func (r *REPL) Run() error {
var err error
r.input, err = readline.NewEx(&readline.Config{
Prompt: r.NumberPrompt(),
HistoryFile: ".repl-history",
})
if err != nil {
return err
}
for {
line, err := r.read()
if err != nil {
switch err.Error() {
case "Interrupt":
r.input.SetPrompt(r.NumberPrompt())
continue
case "Exit":
return nil
}
return err
}
r.Execute(line)
r.lineNumber++
r.input.SetPrompt(r.NumberPrompt())
}
}
// Execute will take a source string and attempt to execute it in the given
// engine context.
func (r *REPL) Execute(src string) {
retSrc := fmt.Sprintf("return (%s)", src)
before := r.engine.StackSize()
// try to run code that forces a return value
err := r.engine.DoString(retSrc)
if err != nil {
// if the customized return injection caused failure, we double check
// by executing the code without it.
err = r.engine.DoString(src)
}
if err != nil {
fmt.Printf("\n <=> %s\n", err.Error())
} else {
var results []*Value
after := r.engine.StackSize() - before
for i := 0; i < after; i++ {
val := r.engine.PopValue()
results = append([]*Value{val}, results...)
}
if len(results) > 0 {
for i := 0; i < len(results); i++ {
str := results[i].Inspect(" ")
fmt.Printf(" => %s\n", str)
}
} else {
fmt.Println(" => nil")
}
}
}
// NumberPrompt returns a formatted prompt to use as the Readline prompt.
func (r *REPL) NumberPrompt() string {
return fmt.Sprintf(r.promptNumFmt, r.lineNumber)
}
// StarPrompt generates a similar prompt to the font with the line number in
// it, but instead of the line number it uses a * character.
func (r *REPL) StarPrompt() string {
n := r.lineNumber
count := 0
for ; n > 0; n /= 10 {
count++
}
if count == 0 {
count = 1
}
return fmt.Sprintf(r.promptStrFmt, strings.Repeat("*", count))
}
// determines if the error means that more code can follow (i.e. multi-line
// input.
func (r *REPL) isIncompleteLine(err error) bool {
if lerr, ok := err.(*glua.ApiError); ok {
if perr, ok := lerr.Cause.(*parse.Error); ok {
return perr.Pos.Line == parse.EOF
}
}
return false
}
func (r *REPL) read() (string, error) {
line, err := r.input.Readline()
if err != nil {
return "", err
}
_, err = r.engine.LoadString("return " + line)
if err == nil {
return line, nil
}
return r.readMulti(line)
}
// read multiline input
func (r *REPL) readMulti(line string) (string, error) {
buf := new(bytes.Buffer)
buf.WriteString(line)
for {
_, err := r.engine.LoadString(buf.String())
if err == nil || !r.isIncompleteLine(err) {
return buf.String(), nil
}
r.input.SetPrompt(r.StarPrompt())
line, err = r.input.Readline()
if err != nil {
return "", err
}
if line == ".exit" {
return "", errExit
}
buf.WriteRune('\n')
buf.WriteString(line)
}
}