-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
339 lines (307 loc) · 8 KB
/
main.go
File metadata and controls
339 lines (307 loc) · 8 KB
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
package main
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/mattn/go-runewidth"
"github.com/yetsing/startprompt/terminalcolor"
// This initializes gpython for runtime execution and is essential.
// It defines forward-declared symbols and registers native built-in modules, such as sys and time.
_ "github.com/go-python/gpython/stdlib"
"github.com/go-python/gpython/py"
"github.com/yetsing/startprompt"
"github.com/yetsing/startprompt/lexer"
"github.com/yetsing/startprompt/token"
)
// 全局的 repl 对象
var grepl *Repl
var keywords = []string{
"False",
"await",
"else",
"import",
"pass",
"None",
"break",
"except",
"in",
"raise",
"True",
"class",
"finally",
"is",
"return",
"and",
"continue",
"for",
"lambda",
"try",
"as",
"def",
"from",
"nonlocal",
"while",
"assert",
"del",
"global",
"not",
"with",
"async",
"elif",
"if",
"or",
"yield",
}
var pyschema = map[token.TokenType]*terminalcolor.ColorStyle{
token.Keyword: terminalcolor.NewFgColorStyleHex("#ee00ee"),
token.Operator: terminalcolor.NewFgColorStyleHex("#aa6666"),
token.Number: terminalcolor.NewFgColorStyleHex("#2aacb8"),
token.String: terminalcolor.NewFgColorStyleHex("#6aab73"),
token.Error: terminalcolor.NewColorStyleHex("#000000", "#ff8888"),
token.Comment: terminalcolor.NewFgColorStyleHex("#0000dd"),
token.CompletionMenuCompletionCurrent: terminalcolor.NewColorStyleHex("#000000", "#dddddd"),
token.CompletionMenuCompletion: terminalcolor.NewColorStyleHex("#ffff88", "#888888"),
token.CompletionMenuProgressButton: terminalcolor.NewColorStyleHex("", "#000000"),
token.CompletionMenuProgressBar: terminalcolor.NewColorStyleHex("", "#aaaaaa"),
token.Prompt: terminalcolor.NewFgColorStyleHex("#004400"),
}
type Prompt struct {
code startprompt.Code
}
func NewPrompt(code startprompt.Code) startprompt.Prompt {
return &Prompt{code: code}
}
func (p *Prompt) GetPrompt() []token.Token {
tk := token.NewToken(token.Prompt, fmt.Sprintf("In [%d]: ", grepl.inputCount))
return []token.Token{tk}
}
func (p *Prompt) GetSecondLinePrefix() []token.Token {
// 拿到默认提示符宽度
var sb strings.Builder
for _, t := range p.GetPrompt() {
sb.WriteString(t.Literal)
}
promptText := sb.String()
spaces := runewidth.StringWidth(promptText) - 5
// 输出类似这样的 "... " ,宽度跟默认提示符一样
return []token.Token{
{
token.PromptSecondLinePrefix,
repeatByte(' ', spaces),
},
{
token.PromptSecondLinePrefix,
repeatByte('.', 3) + ": ",
},
}
}
func isKeyword(name string) bool {
for _, keyword := range keywords {
if keyword == name {
return true
}
}
return false
}
func pyTokens(code string) []token.Token {
l := lexer.NewPy3Lexer(code)
tokens := l.Tokens()
converted := make([]token.Token, len(tokens))
// 更细致的 token 类型
for i, t := range tokens {
if t.TypeIs(token.Name) && isKeyword(t.Literal) {
nt := token.NewToken(token.Keyword, t.Literal)
converted[i] = nt
} else {
converted[i] = t
}
}
return converted
}
type PythonCode struct {
document *startprompt.Document
tokens []token.Token
}
func newMultilineCode(document *startprompt.Document) startprompt.Code {
return &PythonCode{document: document}
}
func (c *PythonCode) GetTokens() []token.Token {
if len(c.tokens) == 0 {
c.tokens = pyTokens(c.document.Text())
}
return c.tokens
}
func (c *PythonCode) Complete() string {
completions := c.GetCompletions()
if len(completions) == 1 {
return completions[0].Suffix
}
return ""
}
func (c *PythonCode) GetCompletions() []*startprompt.Completion {
text := c.document.Text()
head, coms, tail := grepl.Completer(text, c.document.CursorPosition())
if len(coms) == 0 {
return nil
}
// 计算剩余补全的文本 (Suffix)
remainLength := len(text) - len(head) - len(tail)
completions := make([]*startprompt.Completion, len(coms))
for i, com := range coms {
completions[i] = &startprompt.Completion{
Display: com,
Suffix: com[remainLength:],
}
}
return completions
}
func (c *PythonCode) hasIndent() bool {
for _, t := range c.GetTokens() {
if t.TypeIs(token.Indent) {
return true
}
}
return false
}
func (c *PythonCode) ContinueInput() bool {
// 光标不在最后一行,直接换行即可
if !c.document.OnLastLine() {
return true
}
text := c.document.Text()
if len(text) == 0 {
return false
}
_, err := py.Compile(text+"\n", grepl.prog, py.SingleMode, 0, true)
if err != nil {
// 判断是否完整语句,比如 if 2 > 1: 并不是完整的语句,后面还需要有语句
errText := err.Error()
if strings.Contains(errText, "unexpected EOF while parsing") || strings.Contains(errText, "EOF while scanning triple-quoted string literal") {
stripped := strings.TrimSpace(text)
isComment := len(stripped) > 0 && stripped[0] == '#'
return !isComment
}
}
// 如果有缩进,需要连按两次 Enter 才结束当前输入
if c.hasIndent() {
text = strings.TrimRight(text, " ")
return !strings.HasSuffix(text, "\n")
}
return false
}
func (c *PythonCode) CompleteAfterInsertText() bool {
return false
}
// Repl ref: https://github.com/go-python/gpython/blob/main/repl/repl.go
type Repl struct {
Context py.Context
Module *py.Module
prog string
inputCount int
}
func NewRepl(ctx py.Context) *Repl {
if ctx == nil {
ctx = py.NewContext(py.DefaultContextOpts())
}
r := &Repl{
Context: ctx,
prog: "<stdin>",
inputCount: 1,
}
var err error
r.Module, err = ctx.ModuleInit(&py.ModuleImpl{
Info: py.ModuleInfo{
FileDesc: r.prog,
},
})
if err != nil {
panic(err)
}
return r
}
func (r *Repl) Run(line string) {
r.inputCount++
code, err := py.Compile(line+"\n", r.prog, py.SingleMode, 0, true)
if err != nil {
fmt.Printf("compile error: %v\n", err)
return
}
_, err = r.Context.RunCode(code, r.Module.Globals, r.Module.Globals, nil)
if err != nil {
py.TracebackDump(err)
}
}
// Completer 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)
startprompt.DebugLog("partial=%s", partial)
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
}
func main() {
c, err := startprompt.NewCommandLine(&startprompt.CommandLineOption{
CodeFactory: newMultilineCode,
PromptFactory: NewPrompt,
Schema: pyschema,
AutoIndent: true,
EnableDebug: true,
})
if err != nil {
fmt.Printf("failed to startprompt.NewCommandLine: %v\n", err)
return
}
defer c.Close()
grepl = NewRepl(nil)
c.Println(`Type "Ctrl-D" to exit.`)
for {
line, err := c.ReadInput()
if err != nil {
if errors.Is(err, startprompt.ExitError) {
c.Printf("Do you really want to exit ([y]/n)? ")
reply, err := c.ReadRune()
if err != nil {
c.Printf("read error: %v\n", err)
return
}
startprompt.DebugLog("reply %d", reply)
if reply == 'n' {
// 此时不是 raw mode ,所以用户输入需要按下 enter 键之后才能读取到
// 如果不处理掉,就会导致 ReadInput 多出一个 enter 的处理
_, _ = c.ReadRune()
continue
}
} else {
c.Printf("ReadInput error: %v\n", err)
}
return
}
if len(line) == 0 {
continue
}
grepl.Run(line)
c.Printf("\n")
}
}