forked from goby-lang/goby
/
repl.go
366 lines (321 loc) · 8.59 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package igb
import (
"fmt"
parserErr "github.com/goby-lang/goby/compiler/parser/errors"
"io"
"log"
"math/rand"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/chzyer/readline"
"github.com/goby-lang/goby/compiler/bytecode"
"github.com/goby-lang/goby/compiler/lexer"
"github.com/goby-lang/goby/compiler/parser"
"github.com/goby-lang/goby/vm"
"github.com/looplab/fsm"
"github.com/mattn/go-colorable"
)
const (
prmpt1 = "»"
prmpt2 = "¤"
prompt1 = "\033[32m" + prmpt1 + "\033[0m "
prompt2 = "\033[31m" + prmpt2 + "\033[0m "
pad = " "
echo = "\033[33m#»\033[0m"
interrupt = "^C"
semicolon = ";"
exit = "exit"
help = "help"
reset = "reset"
readyToExec = "readyToExec"
Waiting = "waiting"
waitEnded = "waitEnded"
waitExited = "waitExited"
emojis = "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘😗😙😚🙂🤗🤔😐😑😶🙄😏😮😪😴😌😛😜😝🤤🙃🤑😲😭😳🤧😇🤠🤡🤥🤓😈👿👹👺💀👻👽🤖💩😺😸😹😻😼😽"
)
// iGb holds internal states of iGb.
type iGb struct {
sm *fsm.FSM
rl *readline.Instance
completer *readline.PrefixCompleter
lines string
cmds []string
indents int
}
// iVM holds VM only for iGb.
type iVM struct {
v *vm.VM
p *parser.Parser
g *bytecode.Generator
}
var out io.Writer
func init() {
if runtime.GOOS == "windows" {
out = colorable.NewColorableStderr()
} else {
out = os.Stderr
}
}
func println(s ...string) {
out.Write([]byte(strings.Join(s, " ") + "\n"))
}
// StartIgb starts goby's REPL.
func StartIgb(version string) {
reset:
var err error
igb := newIgb()
igb.rl, err = readline.NewEx(&readline.Config{
Prompt: prompt1,
HistoryFile: filepath.Join(os.TempDir(), "readline_goby.tmp"),
AutoComplete: igb.completer,
InterruptPrompt: interrupt,
EOFPrompt: exit,
HistorySearchFold: true,
FuncFilterInputRune: filterInput,
})
defer igb.rl.Close()
if err != nil {
fmt.Printf("iGb error: %s", err)
return
}
log.SetOutput(igb.rl.Stderr())
println("Goby", version, fortune(), fortune(), fortune())
ivm, err := newIVM()
if err != nil {
fmt.Println(err.Error())
return
}
for {
igb, err = readIgb(igb, err)
// Interruption handling
if err != nil {
switch {
case err == io.EOF:
println(igb.lines + "")
return
case err == readline.ErrInterrupt: // Pressing Ctrl-C
if len(igb.lines) == 0 {
if igb.cmds == nil {
println("")
println("Bye!")
return
}
}
// Erasing command buffer
igb.indents = 0
igb.rl.SetPrompt(prompt1)
igb.sm.Event(waitExited)
igb.cmds = nil
println(" -- block cleared")
continue
}
}
// Command handling
switch {
case strings.HasPrefix(igb.lines, "#"):
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
continue
case igb.lines == help:
println(prompt(igb.indents) + igb.lines)
usage(igb.rl.Stderr(), igb.completer)
continue
case igb.lines == reset:
igb.rl = nil
igb.cmds = nil
println(prompt(igb.indents) + igb.lines)
println("Restarting iGb...")
goto reset
case igb.lines == exit:
println(prompt(igb.indents) + igb.lines)
println("Bye!")
return
case igb.lines == "":
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
continue
}
ivm.p.Lexer = lexer.New(igb.lines)
program, perr := ivm.p.ParseProgram()
// Parse error handling
if perr != nil {
switch {
case perr.IsEOF():
if !igb.sm.Is(Waiting) {
igb.sm.Event(Waiting)
}
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
igb.indents++
igb.rl.SetPrompt(prompt(igb.indents) + indent(igb.indents))
igb.cmds = append(igb.cmds, igb.lines)
continue
case perr.IsUnexpectedEnd() && len(igb.cmds) == 0:
// If igb.cmds is empty, it means that user just typed 'end' without corresponding statement/expression
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
igb.indents = 0
igb.rl.SetPrompt(prompt1)
fmt.Println(perr.Message)
igb.cmds = nil
continue
case perr.IsUnexpectedEnd():
if igb.indents > 1 {
igb.indents--
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
igb.sm.Event(Waiting)
igb.rl.SetPrompt(prompt(igb.indents) + indent(igb.indents))
igb.cmds = append(igb.cmds, igb.lines)
continue
}
igb.indents = 0
igb.sm.Event(waitEnded)
igb.rl.SetPrompt(prompt(igb.indents) + indent(igb.indents))
igb.cmds = append(igb.cmds, igb.lines)
}
}
if igb.sm.Is(Waiting) && igb.indents > 0 {
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
igb.rl.SetPrompt(prompt(igb.indents) + indent(igb.indents))
igb.cmds = append(igb.cmds, igb.lines)
continue
}
if igb.sm.Is(waitEnded) {
ivm.p.Lexer = lexer.New(string(strings.Join(igb.cmds, "\n")))
// Test if current input can be properly parsed.
program, perr = ivm.p.ParseProgram()
if perr != nil {
handleParserError(perr, igb)
continue
}
// If everything goes well, reset state and statements buffer
igb.rl.SetPrompt(prompt(igb.indents))
igb.sm.Event(readyToExec)
}
if igb.sm.Is(readyToExec) {
println(prompt(igb.indents) + igb.lines)
if perr != nil {
handleParserError(perr, igb)
continue
}
instructions := ivm.g.GenerateInstructions(program.Statements)
ivm.v.REPLExec(instructions)
r := ivm.v.GetREPLResult()
// Suppress echo back on trailing ';'
if igb.cmds != nil {
if t := igb.cmds[len(igb.cmds)-1]; string(t[len(t)-1]) != semicolon {
println(echo, r)
}
} else {
if string(igb.lines[len(igb.lines)-1]) != semicolon {
println(echo, r)
}
}
//}
igb.cmds = nil
}
}
}
func handleParserError(e *parserErr.Error, igb *iGb) {
if e != nil {
if !e.IsEOF() {
fmt.Println(e.Message)
}
println(prompt(igb.indents) + indent(igb.indents) + igb.lines)
}
}
// Polymorphic helper functions --------------------------------------------
// Other helper functions --------------------------------------------------
// newIgb initializes iGb.
func newIgb() *iGb {
return &iGb{
cmds: nil,
indents: 0,
sm: fsm.NewFSM(
readyToExec,
fsm.Events{
{Name: Waiting, Src: []string{waitEnded, readyToExec}, Dst: Waiting},
{Name: waitEnded, Src: []string{Waiting}, Dst: waitEnded},
{Name: waitExited, Src: []string{Waiting, waitEnded}, Dst: readyToExec},
{Name: readyToExec, Src: []string{waitEnded, readyToExec}, Dst: readyToExec},
},
fsm.Callbacks{},
),
completer: readline.NewPrefixCompleter(
readline.PcItem(help),
readline.PcItem(reset),
readline.PcItem(exit),
),
}
}
//
// newIVM initializes iVM.
func newIVM() (ivm iVM, err error) {
ivm = iVM{}
v, err := vm.New(os.Getenv("GOBY_ROOT"), []string{})
if err != nil {
return ivm, err
}
ivm.v = v
ivm.v.SetClassISIndexTable("")
ivm.v.SetMethodISIndexTable("")
ivm.v.InitForREPL()
// Initialize parser, lexer is not important here
ivm.p = parser.New(lexer.New(""))
ivm.p.Mode = parser.REPLMode
program, _ := ivm.p.ParseProgram()
// Initialize code generator, and it will behavior a little different in REPL mode.
ivm.g = bytecode.NewGenerator()
ivm.g.REPL = true
ivm.g.InitTopLevelScope(program)
return ivm, nil
}
// readIgb fetches one line from input, with helps of Readline lib.
func readIgb(igb *iGb, err error) (*iGb, error) {
igb.rl.Config.UniqueEditLine = true // required to update the previous prompt
igb.lines, err = igb.rl.Readline()
igb.rl.Config.UniqueEditLine = false
igb.lines = strings.TrimSpace(igb.lines)
igb.lines = strings.TrimPrefix(igb.lines, prmpt1)
igb.lines = strings.TrimPrefix(igb.lines, prmpt2)
igb.lines = strings.TrimSpace(igb.lines)
return igb, err
}
// filterInput just ignores Ctrl-z.
func filterInput(r rune) (rune, bool) {
switch r {
case readline.CharCtrlZ:
return r, false
}
return r, true
}
// usage shows help lines.
func usage(w io.Writer, c *readline.PrefixCompleter) {
io.WriteString(w, "commands:\n")
io.WriteString(w, c.Tree(" "))
}
// indent performs indentation with space padding.
func indent(c int) string {
var s string
for i := 0; i < c; i++ {
s = s + pad
}
return s
}
// prompt switches prompt sign.
func prompt(s int) string {
if s > 0 {
return prompt2
}
return prompt1
}
// fortune is just a fun item to show slot machine: receiving rep-digit would imply your fortune ;-)
func fortune() string {
if runtime.GOOS == "windows" {
return ""
}
var randSrc = rand.NewSource(time.Now().UnixNano())
s := strings.Split(emojis, "")
l := len(s)
r := randSrc.Int63() % int64(l)
return s[r]
}