-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathrepl.go
143 lines (131 loc) · 3.55 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
// Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Read Eval Print Loop
package repl
import (
"fmt"
"sort"
"strings"
"github.com/go-python/gpython/py"
"github.com/go-python/gpython/vm"
)
// Possible prompts for the REPL
const (
NormalPrompt = ">>> "
ContinuationPrompt = "... "
)
// Repl state
type REPL struct {
Context py.Context
Module *py.Module
prog string
continuation bool
previous string
term UI
}
// UI implements the user interface for the REPL
type UI interface {
// Set the prompt for the start of line
SetPrompt(string)
// Print a line of output
Print(string)
}
// New create a new REPL and initializes the state machine
func New(ctx py.Context) *REPL {
if ctx == nil {
ctx = py.NewContext(py.DefaultContextOpts())
}
r := &REPL{
Context: ctx,
prog: "<stdin>",
continuation: false,
previous: "",
}
r.Module, _ = ctx.ModuleInit(&py.ModuleImpl{
Info: py.ModuleInfo{
FileDesc: r.prog,
},
})
return r
}
// SetUI initialises the output user interface
func (r *REPL) SetUI(term UI) {
r.term = term
r.term.SetPrompt(NormalPrompt)
}
// Run runs a single line of the REPL
func (r *REPL) Run(line string) {
// Override the PrintExpr output temporarily
oldPrintExpr := vm.PrintExpr
vm.PrintExpr = r.term.Print
defer func() {
vm.PrintExpr = oldPrintExpr
}()
if r.continuation {
if line != "" {
r.previous += string(line) + "\n"
return
}
}
// need +"\n" because "single" expects \n terminated input
toCompile := r.previous + string(line)
if toCompile == "" {
return
}
code, err := py.Compile(toCompile+"\n", r.prog, py.SingleMode, 0, true)
if err != nil {
// Detect that we should start a continuation line
// FIXME detect EOF properly!
errText := err.Error()
if strings.Contains(errText, "unexpected EOF while parsing") || strings.Contains(errText, "EOF while scanning triple-quoted string literal") {
stripped := strings.TrimSpace(toCompile)
isComment := len(stripped) > 0 && stripped[0] == '#'
if !isComment {
r.continuation = true
r.previous += string(line) + "\n"
r.term.SetPrompt(ContinuationPrompt)
}
return
}
}
r.continuation = false
r.term.SetPrompt(NormalPrompt)
r.previous = ""
if err != nil {
r.term.Print(fmt.Sprintf("Compile error: %v", err))
return
}
_, err = r.Context.RunCode(code, r.Module.Globals, r.Module.Globals, nil)
if err != nil {
py.TracebackDump(err)
}
}
// WordCompleter takes the currently edited line with the cursor
// position and returns the completion candidates for the partial word
// to be completed. If the line is "Hello, wo!!!" and the cursor is
// before the first '!', ("Hello, wo!!!", 9) is passed to the
// completer which may returns ("Hello, ", {"world", "Word"}, "!!!")
// to have "Hello, world!!!".
func (r *REPL) Completer(line string, pos int) (head string, completions []string, tail string) {
head = line[:pos]
tail = line[pos:]
lastSpace := strings.LastIndex(head, " ")
head, partial := line[:lastSpace+1], line[lastSpace+1:]
// log.Printf("head = %q, partial = %q, tail = %q", head, partial, tail)
found := make(map[string]struct{})
match := func(d py.StringDict) {
for k := range d {
if strings.HasPrefix(k, partial) {
if _, ok := found[k]; !ok {
completions = append(completions, k)
found[k] = struct{}{}
}
}
}
}
match(r.Module.Globals)
match(r.Context.Store().Builtins.Globals)
sort.Strings(completions)
return head, completions, tail
}