forked from cosmos72/gomacro
/
repl.go
602 lines (536 loc) · 14.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
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/*
* gomacro - A Go interpreter with Lisp-like macros
*
* Copyright (C) 2018-2019 Massimiliano Ghilardi
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*
* repl.go
*
* Created on: Apr 28, 2018
* Author: Massimiliano Ghilardi
*/
package fast
import (
"bufio"
"go/ast"
"go/token"
"os"
"runtime/debug"
"sort"
"strings"
"time"
"github.com/lifepod-solutions/gomacro/ast2"
"github.com/lifepod-solutions/gomacro/base"
"github.com/lifepod-solutions/gomacro/base/paths"
"github.com/lifepod-solutions/gomacro/base/reflect"
bstrings "github.com/lifepod-solutions/gomacro/base/strings"
xr "github.com/lifepod-solutions/gomacro/xreflect"
)
// return read string and position of first non-comment token.
// return "", -1 on EOF
func (ir *Interp) Read() (string, int) {
g := &ir.Comp.Globals
var opts base.ReadOptions
if g.Options&base.OptShowPrompt != 0 {
opts |= base.ReadOptShowPrompt
}
src, firstToken := g.ReadMultiline(opts, ir.Comp.Prompt)
if firstToken < 0 {
g.IncLine(src)
} else if firstToken > 0 {
g.IncLine(src[0:firstToken])
}
return src, firstToken
}
// parse + macroexpansion + collect declarations & statements
func (ir *Interp) Parse(src string) ast2.Ast {
if len(src) == 0 {
return nil
}
form := ir.Comp.Parse(src)
if form == nil {
return nil
}
// collect phase
g := &ir.Comp.Globals
if g.Options&(base.OptCollectDeclarations|base.OptCollectStatements) != 0 {
g.CollectAst(form)
}
return form
}
// combined Parse + Compile
func (ir *Interp) Compile(src string) *Expr {
return ir.CompileAst(ir.Parse(src))
}
func (ir *Interp) CompileNode(node ast.Node) *Expr {
return ir.CompileAst(ast2.ToAst(node))
}
func (ir *Interp) CompileAst(form ast2.Ast) *Expr {
if form == nil {
return nil
}
c := ir.Comp
g := c.CompGlobals
if g.Options&base.OptMacroExpandOnly != 0 {
x := form.Interface()
return c.exprValue(c.TypeOf(x), x)
}
// compile phase
expr := c.Compile(form)
if g.Options&base.OptKeepUntyped == 0 && expr != nil && expr.Untyped() {
expr.ConstTo(expr.DefaultType())
}
if g.Options&base.OptShowCompile != 0 {
g.Fprintf(g.Stdout, "%v\n", expr)
}
return expr
}
// run without debugging. to execute with single-step debugging, use Interp.DebugExpr() instead
func (ir *Interp) RunExpr1(e *Expr) (xr.Value, xr.Type) {
if e == nil {
return None, nil
}
// do NOT use e.AsX1(), it converts untyped constants to their default type => may overflow
e.CheckX1()
vs, ts := ir.RunExpr(e)
return vs[0], ts[0]
}
// run without debugging. to execute with single-step debugging, use Interp.DebugExpr() instead
func (ir *Interp) RunExpr(e *Expr) ([]xr.Value, []xr.Type) {
if e == nil {
return nil, nil
}
env := ir.PrepareEnv()
if ir.Comp.Globals.Options&base.OptKeepUntyped == 0 && e.Untyped() {
e.ConstTo(e.DefaultType())
}
run := env.Run
run.applyDebugOp(DebugOpContinue)
defer run.setCurrEnv(run.setCurrEnv(env))
fun := e.AsXV(COptKeepUntyped)
v, vs := fun(env)
return reflect.PackValues(v, vs), reflect.PackTypes(e.Type, e.Types)
}
// execute with single-step debugging. to run without debugging, use Interp.RunExpr() instead
func (ir *Interp) DebugExpr1(e *Expr) (xr.Value, xr.Type) {
if e == nil {
return None, nil
}
// do NOT use e.AsX1(), it converts untyped constants to their default type => may overflow
e.CheckX1()
vs, ts := ir.DebugExpr(e)
return vs[0], ts[0]
}
// execute with single-step debugging. to run without debugging, use Interp.RunExpr() instead
func (ir *Interp) DebugExpr(e *Expr) ([]xr.Value, []xr.Type) {
if e == nil {
return nil, nil
}
env := ir.PrepareEnv()
if ir.Comp.Globals.Options&base.OptKeepUntyped == 0 && e.Untyped() {
e.ConstTo(e.DefaultType())
}
run := env.Run
run.applyDebugOp(DebugOpStep)
defer run.setCurrEnv(run.setCurrEnv(env))
fun := e.AsXV(COptKeepUntyped)
v, vs := fun(env)
return reflect.PackValues(v, vs), reflect.PackTypes(e.Type, e.Types)
}
// combined Parse + Compile + DebugExpr
func (ir *Interp) Debug(src string) ([]xr.Value, []xr.Type) {
return ir.DebugExpr(ir.Compile(src))
}
// set CurrEnv, returns previous value
func (g *Run) setCurrEnv(env *Env) *Env {
old := g.CurrEnv
g.CurrEnv = env
return old
}
// ================ PrepareEnv() ========================
func (ir *Interp) PrepareEnv() *Env {
// allocate Env.Ints[] in large chunks while we can:
// once an Env.Ints[idx] address is taken, we can no longer reallocate it
return ir.prepareEnv(16, 1024)
}
func (ir *Interp) prepareEnv(minValDelta int, minIntDelta int) *Env {
c := ir.Comp
env := ir.env
// usually we know at Env creation how many slots are needed in c.Env.Binds
// but here we are modifying an existing Env...
if minValDelta < 0 {
minValDelta = 0
}
if minIntDelta < 0 {
minIntDelta = 0
}
capacity, min := cap(env.Vals), c.BindNum
// c.Debugf("prepareEnv() before: c.BindNum = %v, minValDelta = %v, len(env.Binds) = %v, cap(env.Binds) = %v, env = %p", c.BindNum, minValDelta, len(env.Binds), cap(env.Binds), env)
if capacity < min {
capacity *= 2
if capacity < min {
capacity = min
}
if capacity-cap(env.Vals) < minValDelta {
capacity = cap(env.Vals) + minValDelta
}
binds := make([]xr.Value, min, capacity)
copy(binds, env.Vals)
env.Vals = binds
}
if len(env.Vals) < min {
env.Vals = env.Vals[0:min:cap(env.Vals)]
}
// c.Debugf("prepareEnv() after: c.BindNum = %v, minDelta = %v, len(env.Binds) = %v, cap(env.Binds) = %v, env = %p", c.BindNum, minDelta, len(env.Binds), cap(env.Binds), env)
capacity, min = cap(env.Ints), c.IntBindNum
if capacity < min {
if env.IntAddressTaken {
c.Errorf("internal error: attempt to reallocate Env.Ints[] after one of its addresses was taken")
}
capacity *= 2
if capacity < min {
capacity = min
}
if capacity-cap(env.Ints) < minIntDelta {
capacity = cap(env.Ints) + minIntDelta
}
binds := make([]uint64, min, capacity)
copy(binds, env.Ints)
env.Ints = binds
}
if len(env.Ints) < min {
env.Ints = env.Ints[0:min:cap(env.Ints)] // does not reallocate
}
if env.IntAddressTaken {
c.IntBindMax = cap(env.Ints)
}
g := env.Run
// do NOT set g.CurrEnv = env, it messes up the call stack. done by Interp.RunExpr* and Interp.DebugExpr*
// g.CurrEnv = env
// in case we received a SigInterrupt in the meantime
g.Signals.Sync = base.SigNone
g.Signals.Async = base.SigNone
if g.Options&base.OptDebugger != 0 {
// for debugger
env.DebugComp = c
} else {
env.DebugComp = nil
}
return env
}
// ====================== Repl() and friends =====================
var historyfile = paths.Subdir(paths.UserHomeDir(), ".gomacro_history")
func (ir *Interp) ReplStdin() {
g := ir.Comp.CompGlobals
if g.Options&base.OptShowPrompt != 0 {
g.Fprintf(g.Stdout, `// Welcome to gomacro. Type %chelp for help, %ccopy for copyright and license.
// This is free software with ABSOLUTELY NO WARRANTY.
`, g.ReplCmdChar, g.ReplCmdChar)
}
tty, _ := base.MakeTtyReadline(historyfile)
defer tty.Close(historyfile) // restore normal tty mode
ch := base.StartSignalHandler(ir.Interrupt)
defer base.StopSignalHandler(ch)
savetty := g.Readline
g.Readline = tty
defer func() {
g.Readline = savetty
}()
tty.Term.SetWordCompleter(ir.CompleteWords)
g.Line = 0
for ir.ReadParseEvalPrint() {
g.Line = 0
}
os.Stdout.WriteString("\n")
}
func (ir *Interp) Repl(in *bufio.Reader) {
g := ir.Comp.CompGlobals
r := base.MakeBufReadline(in)
ch := base.StartSignalHandler(ir.Interrupt)
defer base.StopSignalHandler(ch)
savetty := g.Readline
g.Readline = r
defer func() {
g.Readline = savetty
}()
for ir.ReadParseEvalPrint() {
}
}
func (ir *Interp) ReadParseEvalPrint() (callAgain bool) {
src, firstToken := ir.Read()
if firstToken < 0 {
// skip comment-only lines and continue, but fail on EOF or other errors
return len(src) != 0
}
return ir.ParseEvalPrint(src)
}
func (ir *Interp) ParseEvalPrint(src string) (callAgain bool) {
if len(src) == 0 || len(strings.TrimSpace(src)) == 0 {
return true // no input => no form
}
t1, trap, duration := ir.beforeEval()
defer ir.afterEval(src, &callAgain, &trap, t1, duration)
src, opt := ir.Cmd(src)
callAgain = opt&base.CmdOptQuit == 0
if len(src) == 0 || !callAgain {
trap = false // no panic happened
return callAgain
}
g := &ir.Comp.Globals
if toenable := cmdOptForceEval(g, opt); toenable != 0 {
defer func() {
g.Options |= toenable
}()
}
ir.env.Run.CmdOpt = opt // store options where Interp.Interrupt() can find them
// parse + macroexpansion
form := ir.Parse(src)
// compile
expr := ir.CompileAst(form)
// run expression
values, types := ir.RunExpr(expr)
// print phase
g.Print(values, types)
trap = false // no panic happened
return callAgain
}
func (ir *Interp) beforeEval() (t1 time.Time, trap bool, duration bool) {
g := &ir.Comp.Globals
trap = g.Options&base.OptTrapPanic != 0
duration = g.Options&base.OptShowTime != 0
if duration {
t1 = time.Now()
}
return t1, trap, duration
}
func (ir *Interp) afterEval(src string, callAgain *bool, trap *bool, t1 time.Time, duration bool) {
g := &ir.Comp.Globals
g.IncLine(src)
if *trap {
rec := recover()
if g.Options&base.OptPanicStackTrace != 0 {
g.Fprintf(g.Stderr, "%v\n%s", rec, debug.Stack())
} else {
g.Fprintf(g.Stderr, "%v\n", rec)
}
*callAgain = true
}
if duration {
delta := time.Since(t1)
g.Debugf("eval time %v", delta)
}
}
func cmdOptForceEval(g *base.Globals, opt base.CmdOpt) (toenable base.Options) {
if opt&base.CmdOptForceEval != 0 {
// temporarily disable collection of declarations and statements,
// and temporarily re-enable eval (i.e. disable macroexpandonly)
const todisable = base.OptMacroExpandOnly | base.OptCollectDeclarations | base.OptCollectStatements
if g.Options&todisable != 0 {
g.Options &^= todisable
return todisable
}
}
return 0
}
// implement code completion API github.com/pererh/liner.WordCompleter
// Currently only supports global symbols and imported packages,
// optionally followed by a dot-separated sequence of field or method names,
// including embedded fields and wrapper methods.
func (ir *Interp) CompleteWords(line string, pos int) (head string, completions []string, tail string) {
if pos > len(line) {
pos = len(line)
}
head = line[:pos]
tail = line[pos:]
words := strings.Split(head, ".")
n := len(words)
// find the longest sequence of ident.ident.ident...
for i := n - 1; i >= 0; i-- {
// ignore spaces before and after identifiers
words[i] = strings.TrimSpace(words[i])
if i == n-1 && len(words[i]) == 0 {
// last word can be empty: it means TAB immediately after '.'
continue
}
word := TailIdentifier(words[i])
if len(word) != len(words[i]) {
if len(word) != 0 {
words[i] = word
} else {
i++
}
words = words[i:]
break
}
}
completions = ir.Comp.CompleteWords(words)
if len(completions) != 0 {
fixed := len(head) - len(TailIdentifier(head))
pos := strings.LastIndexByte(head, '.')
if pos >= 0 && pos >= fixed {
head = head[:pos+1]
} else {
head = head[:fixed]
}
}
return head, completions, tail
}
// implement code completion on ident.ident.ident.ident...
func (c *Comp) CompleteWords(words []string) []string {
var completions []string
switch len(words) {
case 0:
case 1:
completions = c.completeWord(words[0])
default:
var node interface{}
if sym := c.TryResolve(words[0]); sym != nil {
node = &sym.Bind
} else if typ := c.TryResolveType(words[0]); typ != nil {
node = typ
} else {
break
}
completions = c.completeWords(node, words[1:])
}
return completions
}
func (c *Comp) completeWords(node interface{}, words []string) []string {
i, n := 0, len(words)
for i+1 < n {
switch obj := node.(type) {
case *Bind:
if obj.Const() {
if imp, ok := obj.Value.(*Import); ok {
// complete on imported package contents
node = imp
continue
}
}
// complete on symbol type
node = obj.Type
continue
case *Import:
if i != 0 {
break
} else if bind := obj.Binds[words[i]]; bind != nil {
// complete on imported package binds
node = bind
i++
continue
} else if typ := obj.Types[words[i]]; typ != nil {
// complete on imported package types
node = typ
i++
continue
}
case xr.Type:
field, fieldok, _, _, err := c.TryLookupFieldOrMethod(obj, words[i])
if err != nil {
break
} else if fieldok {
node = field.Type
i++
continue
}
// {type,value}.method.anything will never compile
}
return nil
}
return c.completeLastWord(node, words[i])
}
var keywords []string
func init() {
lo, hi := token.BREAK, token.VAR
keywords = make([]string, hi-lo+3)
for tok := lo; tok <= hi; tok++ {
keywords[tok-lo] = tok.String()
}
keywords[hi-lo+1] = "macro"
keywords[hi-lo+2] = "template"
}
// complete a single, partial word
func (c *Comp) completeWord(word string) []string {
var completions []string
if size := len(word); size != 0 {
// complete binds and types
for co := c; co != nil; co = co.Outer {
for name := range co.Binds {
if len(name) >= size && name[:size] == word {
completions = append(completions, name)
}
}
for name := range co.Types {
if len(name) >= size && name[:size] == word {
completions = append(completions, name)
}
}
}
// complete keywords
for _, name := range keywords {
if len(name) >= size && name[:size] == word {
completions = append(completions, name)
}
}
}
return sortUnique(completions)
}
// complete the last partial word of a sequence ident.ident.ident...
func (c *Comp) completeLastWord(node interface{}, word string) []string {
var completions []string
size := len(word)
for {
switch obj := node.(type) {
case *Bind:
if obj.Const() {
if imp, ok := obj.Value.(*Import); ok {
// complete on imported package contents
node = imp
continue
}
}
// complete on symbol type
node = obj.Type
continue
case *Import:
for name := range obj.Binds {
if len(name) >= size && name[:size] == word {
completions = append(completions, name)
}
}
for name := range obj.Types {
if len(name) >= size && name[:size] == word {
completions = append(completions, name)
}
}
case xr.Type:
completions = c.listFieldsAndMethods(obj, word)
}
break
}
return sortUnique(completions)
}
// return the trailing substring of s that is a valid identifier
func TailIdentifier(s string) string {
return bstrings.TailIdentifier(s)
}
func sortUnique(vec []string) []string {
if n := len(vec); n > 1 {
sort.Strings(vec)
prev := vec[0]
j := 1
for i := 1; i < n; i++ {
if s := vec[i]; s != prev {
vec[j] = s
prev = s
j++
}
}
vec = vec[:j]
}
return vec
}