Debian Codegraph @

interp/interp.go

raw symbols SCIP
1 package interp
2
3 import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "go/build"
9 "go/scanner"
10 "go/token"
11 "io"
12 "io/fs"
13 "os"
14 "os/signal"
15 "path"
16 "path/filepath"
17 "reflect"
18 "runtime"
19 "runtime/debug"
20 "strconv"
21 "strings"
22 "sync"
23 "sync/atomic"
24 )
25
26 // Interpreter node structure for AST and CFG.
27 type node struct {
28 debug *nodeDebugData // debug info
29 child []*node // child subtrees (AST)
30 anc *node // ancestor (AST)
31 param []*itype // generic parameter nodes (AST)
32 start *node // entry point in subtree (CFG)
33 tnext *node // true branch successor (CFG)
34 fnext *node // false branch successor (CFG)
35 interp *Interpreter // interpreter context
36 index int64 // node index (dot display)
37 findex int // index of value in frame or frame size (func def, type def)
38 level int // number of frame indirections to access value
39 nleft int // number of children in left part (assign) or indicates preceding type (compositeLit)
40 nright int // number of children in right part (assign)
41 kind nkind // kind of node
42 pos token.Pos // position in source code, relative to fset
43 sym *symbol // associated symbol
44 typ *itype // type of value in frame, or nil
45 recv *receiver // method receiver node for call, or nil
46 types []reflect.Type // frame types, used by function literals only
47 scope *scope // frame scope
48 action action // action
49 exec bltn // generated function to execute
50 gen bltnGenerator // generator function to produce above bltn
51 val interface{} // static generic value (CFG execution)
52 rval reflect.Value // reflection value to let runtime access interpreter (CFG)
53 ident string // set if node is a var or func
54 redeclared bool // set if node is a redeclared variable (CFG)
55 meta interface{} // meta stores meta information between gta runs, like errors
56 }
57
58 func (n *node) shouldBreak() bool {
59 if n == nil || n.debug == nil {
60 return false
61 }
62
63 if n.debug.breakOnLine || n.debug.breakOnCall {
64 return true
65 }
66
67 return false
68 }
69
70 func (n *node) setProgram(p *Program) {
71 if n.debug == nil {
72 n.debug = new(nodeDebugData)
73 }
74 n.debug.program = p
75 }
76
77 func (n *node) setBreakOnCall(v bool) {
78 if n.debug == nil {
79 if !v {
80 return
81 }
82 n.debug = new(nodeDebugData)
83 }
84 n.debug.breakOnCall = v
85 }
86
87 func (n *node) setBreakOnLine(v bool) {
88 if n.debug == nil {
89 if !v {
90 return
91 }
92 n.debug = new(nodeDebugData)
93 }
94 n.debug.breakOnLine = v
95 }
96
97 // receiver stores method receiver object access path.
98 type receiver struct {
99 node *node // receiver value for alias and struct types
100 val reflect.Value // receiver value for interface type and value type
101 index []int // path in receiver value for interface or value type
102 }
103
104 // frame contains values for the current execution level (a function context).
105 type frame struct {
106 // id is an atomic counter used for cancellation, only accessed
107 // via newFrame/runid/setrunid/clone.
108 // Located at start of struct to ensure proper alignment.
109 id uint64
110
111 debug *frameDebugData
112
113 root *frame // global space
114 anc *frame // ancestor frame (caller space)
115 data []reflect.Value // values
116
117 mutex sync.RWMutex
118 deferred [][]reflect.Value // defer stack
119 recovered interface{} // to handle panic recover
120 done reflect.SelectCase // for cancellation of channel operations
121 }
122
123 func newFrame(anc *frame, length int, id uint64) *frame {
124 f := &frame{
125 anc: anc,
126 data: make([]reflect.Value, length),
127 id: id,
128 }
129 if anc == nil {
130 f.root = f
131 } else {
132 f.done = anc.done
133 f.root = anc.root
134 }
135 return f
136 }
137
138 func (f *frame) runid() uint64 { return atomic.LoadUint64(&f.id) }
139 func (f *frame) setrunid(id uint64) { atomic.StoreUint64(&f.id, id) }
140 func (f *frame) clone() *frame {
141 f.mutex.RLock()
142 defer f.mutex.RUnlock()
143 nf := &frame{
144 anc: f.anc,
145 root: f.root,
146 deferred: f.deferred,
147 recovered: f.recovered,
148 id: f.runid(),
149 done: f.done,
150 debug: f.debug,
151 }
152 nf.data = make([]reflect.Value, len(f.data))
153 copy(nf.data, f.data)
154 return nf
155 }
156
157 // Exports stores the map of binary packages per package path.
158 // The package path is the path joined from the import path and the package name
159 // as specified in source files by the "package" statement.
160 type Exports map[string]map[string]reflect.Value
161
162 // imports stores the map of source packages per package path.
163 type imports map[string]map[string]*symbol
164
165 // opt stores interpreter options.
166 type opt struct {
167 // dotCmd is the command to process the dot graph produced when astDot and/or
168 // cfgDot is enabled. It defaults to 'dot -Tdot -o <filename>.dot'.
169 dotCmd string
170 context build.Context // build context: GOPATH, build constraints
171 stdin io.Reader // standard input
172 stdout io.Writer // standard output
173 stderr io.Writer // standard error
174 args []string // cmdline args
175 env map[string]string // environment of interpreter, entries in form of "key=value"
176 filesystem fs.FS // filesystem containing sources
177 astDot bool // display AST graph (debug)
178 cfgDot bool // display CFG graph (debug)
179 noRun bool // compile, but do not run
180 fastChan bool // disable cancellable chan operations
181 specialStdio bool // allows os.Stdin, os.Stdout, os.Stderr to not be file descriptors
182 unrestricted bool // allow use of non-sandboxed symbols
183 }
184
185 // Interpreter contains global resources and state.
186 type Interpreter struct {
187 // id is an atomic counter used for run cancellation,
188 // only accessed via runid/stop
189 // Located at start of struct to ensure proper alignment on 32-bit
190 // architectures.
191 id uint64
192
193 // nindex is a node number incremented for each new node.
194 // It is used for debug (AST and CFG graphs). As it is atomically
195 // incremented, keep it aligned on 64 bits boundary.
196 nindex int64
197
198 name string // name of the input source file (or main)
199
200 opt // user settable options
201 cancelChan bool // enables cancellable chan operations
202 fset *token.FileSet // fileset to locate node in source code
203 binPkg Exports // binary packages used in interpreter, indexed by path
204 rdir map[string]bool // for src import cycle detection
205 mapTypes map[reflect.Value][]reflect.Type // special interfaces mapping for wrappers
206
207 mutex sync.RWMutex
208 frame *frame // program data storage during execution
209 universe *scope // interpreter global level scope
210 scopes map[string]*scope // package level scopes, indexed by import path
211 srcPkg imports // source packages used in interpreter, indexed by path
212 pkgNames map[string]string // package names, indexed by import path
213 done chan struct{} // for cancellation of channel operations
214 roots []*node
215 generic map[string]*node
216
217 hooks *hooks // symbol hooks
218
219 debugger *Debugger
220 }
221
222 const (
223 mainID = "main"
224 selfPrefix = "github.com/traefik/yaegi"
225 selfPath = selfPrefix + "/interp/interp"
226 // DefaultSourceName is the name used by default when the name of the input
227 // source file has not been specified for an Eval.
228 // TODO(mpl): something even more special as a name?
229 DefaultSourceName = "_.go"
230
231 // Test is the value to pass to EvalPath to activate evaluation of test functions.
232 Test = false
233 // NoTest is the value to pass to EvalPath to skip evaluation of test functions.
234 NoTest = true
235 )
236
237 // Self points to the current interpreter if accessed from within itself, or is nil.
238 var Self *Interpreter
239
240 // Symbols exposes interpreter values.
241 var Symbols = Exports{
242 selfPath: map[string]reflect.Value{
243 "New": reflect.ValueOf(New),
244
245 "Interpreter": reflect.ValueOf((*Interpreter)(nil)),
246 "Options": reflect.ValueOf((*Options)(nil)),
247 "Panic": reflect.ValueOf((*Panic)(nil)),
248 },
249 }
250
251 func init() { Symbols[selfPath]["Symbols"] = reflect.ValueOf(Symbols) }
252
253 // _error is a wrapper of error interface type.
254 type _error struct {
255 IValue interface{}
256 WError func() string
257 }
258
259 func (w _error) Error() string { return w.WError() }
260
261 // Panic is an error recovered from a panic call in interpreted code.
262 type Panic struct {
263 // Value is the recovered value of a call to panic.
264 Value interface{}
265
266 // Callers is the call stack obtained from the recover call.
267 // It may be used as the parameter to runtime.CallersFrames.
268 Callers []uintptr
269
270 // Stack is the call stack buffer for debug.
271 Stack []byte
272 }
273
274 // TODO: Capture interpreter stack frames also and remove
275 // fmt.Fprintln(n.interp.stderr, oNode.cfgErrorf("panic")) in runCfg.
276
277 func (e Panic) Error() string { return fmt.Sprint(e.Value) }
278
279 // Walk traverses AST n in depth first order, call cbin function
280 // at node entry and cbout function at node exit.
281 func (n *node) Walk(in func(n *node) bool, out func(n *node)) {
282 if in != nil && !in(n) {
283 return
284 }
285 for _, child := range n.child {
286 child.Walk(in, out)
287 }
288 if out != nil {
289 out(n)
290 }
291 }
292
293 // Options are the interpreter options.
294 type Options struct {
295 // GoPath sets GOPATH for the interpreter.
296 GoPath string
297
298 // BuildTags sets build constraints for the interpreter.
299 BuildTags []string
300
301 // Standard input, output and error streams.
302 // They default to os.Stdin, os.Stdout and os.Stderr respectively.
303 Stdin io.Reader
304 Stdout, Stderr io.Writer
305
306 // Cmdline args, defaults to os.Args.
307 Args []string
308
309 // Environment of interpreter. Entries are in the form "key=values".
310 Env []string
311
312 // SourcecodeFilesystem is where the _sourcecode_ is loaded from and does
313 // NOT affect the filesystem of scripts when they run.
314 // It can be any fs.FS compliant filesystem (e.g. embed.FS, or fstest.MapFS for testing)
315 // See example/fs/fs_test.go for an example.
316 SourcecodeFilesystem fs.FS
317
318 // Unrestricted allows to run non sandboxed stdlib symbols such as os/exec and environment
319 Unrestricted bool
320 }
321
322 // New returns a new interpreter.
323 func New(options Options) *Interpreter {
324 i := Interpreter{
325 opt: opt{context: build.Default, filesystem: &realFS{}, env: map[string]string{}},
326 frame: newFrame(nil, 0, 0),
327 fset: token.NewFileSet(),
328 universe: initUniverse(),
329 scopes: map[string]*scope{},
330 binPkg: Exports{"": map[string]reflect.Value{"_error": reflect.ValueOf((*_error)(nil))}},
331 mapTypes: map[reflect.Value][]reflect.Type{},
332 srcPkg: imports{},
333 pkgNames: map[string]string{},
334 rdir: map[string]bool{},
335 hooks: &hooks{},
336 generic: map[string]*node{},
337 }
338
339 if i.opt.stdin = options.Stdin; i.opt.stdin == nil {
340 i.opt.stdin = os.Stdin
341 }
342
343 if i.opt.stdout = options.Stdout; i.opt.stdout == nil {
344 i.opt.stdout = os.Stdout
345 }
346
347 if i.opt.stderr = options.Stderr; i.opt.stderr == nil {
348 i.opt.stderr = os.Stderr
349 }
350
351 if i.opt.args = options.Args; i.opt.args == nil {
352 i.opt.args = os.Args
353 }
354
355 // unrestricted allows to use non sandboxed stdlib symbols and env.
356 if options.Unrestricted {
357 i.opt.unrestricted = true
358 } else {
359 for _, e := range options.Env {
360 a := strings.SplitN(e, "=", 2)
361 if len(a) == 2 {
362 i.opt.env[a[0]] = a[1]
363 } else {
364 i.opt.env[a[0]] = ""
365 }
366 }
367 }
368
369 if options.SourcecodeFilesystem != nil {
370 i.opt.filesystem = options.SourcecodeFilesystem
371 }
372
373 i.opt.context.GOPATH = options.GoPath
374 if len(options.BuildTags) > 0 {
375 i.opt.context.BuildTags = options.BuildTags
376 }
377
378 // astDot activates AST graph display for the interpreter
379 i.opt.astDot, _ = strconv.ParseBool(os.Getenv("YAEGI_AST_DOT"))
380
381 // cfgDot activates CFG graph display for the interpreter
382 i.opt.cfgDot, _ = strconv.ParseBool(os.Getenv("YAEGI_CFG_DOT"))
383
384 // dotCmd defines how to process the dot code generated whenever astDot and/or
385 // cfgDot is enabled. It defaults to 'dot -Tdot -o<filename>.dot' where filename
386 // is context dependent.
387 i.opt.dotCmd = os.Getenv("YAEGI_DOT_CMD")
388
389 // noRun disables the execution (but not the compilation) in the interpreter
390 i.opt.noRun, _ = strconv.ParseBool(os.Getenv("YAEGI_NO_RUN"))
391
392 // fastChan disables the cancellable version of channel operations in evalWithContext
393 i.opt.fastChan, _ = strconv.ParseBool(os.Getenv("YAEGI_FAST_CHAN"))
394
395 // specialStdio allows to assign directly io.Writer and io.Reader to os.Stdxxx,
396 // even if they are not file descriptors.
397 i.opt.specialStdio, _ = strconv.ParseBool(os.Getenv("YAEGI_SPECIAL_STDIO"))
398
399 return &i
400 }
401
402 const (
403 bltnAlignof = "unsafe.Alignof"
404 bltnAppend = "append"
405 bltnCap = "cap"
406 bltnClose = "close"
407 bltnComplex = "complex"
408 bltnImag = "imag"
409 bltnCopy = "copy"
410 bltnDelete = "delete"
411 bltnLen = "len"
412 bltnMake = "make"
413 bltnNew = "new"
414 bltnOffsetof = "unsafe.Offsetof"
415 bltnPanic = "panic"
416 bltnPrint = "print"
417 bltnPrintln = "println"
418 bltnReal = "real"
419 bltnRecover = "recover"
420 bltnSizeof = "unsafe.Sizeof"
421 )
422
423 func initUniverse() *scope {
424 sc := &scope{global: true, sym: map[string]*symbol{
425 // predefined Go types
426 "any": {kind: typeSym, typ: &itype{cat: interfaceT, str: "any"}},
427 "bool": {kind: typeSym, typ: &itype{cat: boolT, name: "bool", str: "bool"}},
428 "byte": {kind: typeSym, typ: &itype{cat: uint8T, name: "uint8", str: "uint8"}},
429 "comparable": {kind: typeSym, typ: &itype{cat: comparableT, name: "comparable", str: "comparable"}},
430 "complex64": {kind: typeSym, typ: &itype{cat: complex64T, name: "complex64", str: "complex64"}},
431 "complex128": {kind: typeSym, typ: &itype{cat: complex128T, name: "complex128", str: "complex128"}},
432 "error": {kind: typeSym, typ: &itype{cat: errorT, name: "error", str: "error"}},
433 "float32": {kind: typeSym, typ: &itype{cat: float32T, name: "float32", str: "float32"}},
434 "float64": {kind: typeSym, typ: &itype{cat: float64T, name: "float64", str: "float64"}},
435 "int": {kind: typeSym, typ: &itype{cat: intT, name: "int", str: "int"}},
436 "int8": {kind: typeSym, typ: &itype{cat: int8T, name: "int8", str: "int8"}},
437 "int16": {kind: typeSym, typ: &itype{cat: int16T, name: "int16", str: "int16"}},
438 "int32": {kind: typeSym, typ: &itype{cat: int32T, name: "int32", str: "int32"}},
439 "int64": {kind: typeSym, typ: &itype{cat: int64T, name: "int64", str: "int64"}},
440 "interface{}": {kind: typeSym, typ: &itype{cat: interfaceT, str: "interface{}"}},
441 "rune": {kind: typeSym, typ: &itype{cat: int32T, name: "int32", str: "int32"}},
442 "string": {kind: typeSym, typ: &itype{cat: stringT, name: "string", str: "string"}},
443 "uint": {kind: typeSym, typ: &itype{cat: uintT, name: "uint", str: "uint"}},
444 "uint8": {kind: typeSym, typ: &itype{cat: uint8T, name: "uint8", str: "uint8"}},
445 "uint16": {kind: typeSym, typ: &itype{cat: uint16T, name: "uint16", str: "uint16"}},
446 "uint32": {kind: typeSym, typ: &itype{cat: uint32T, name: "uint32", str: "uint32"}},
447 "uint64": {kind: typeSym, typ: &itype{cat: uint64T, name: "uint64", str: "uint64"}},
448 "uintptr": {kind: typeSym, typ: &itype{cat: uintptrT, name: "uintptr", str: "uintptr"}},
449
450 // predefined Go constants
451 "false": {kind: constSym, typ: untypedBool(nil), rval: reflect.ValueOf(false)},
452 "true": {kind: constSym, typ: untypedBool(nil), rval: reflect.ValueOf(true)},
453 "iota": {kind: constSym, typ: untypedInt(nil)},
454
455 // predefined Go zero value
456 "nil": {typ: &itype{cat: nilT, untyped: true, str: "nil"}},
457
458 // predefined Go builtins
459 bltnAppend: {kind: bltnSym, builtin: _append},
460 bltnCap: {kind: bltnSym, builtin: _cap},
461 bltnClose: {kind: bltnSym, builtin: _close},
462 bltnComplex: {kind: bltnSym, builtin: _complex},
463 bltnImag: {kind: bltnSym, builtin: _imag},
464 bltnCopy: {kind: bltnSym, builtin: _copy},
465 bltnDelete: {kind: bltnSym, builtin: _delete},
466 bltnLen: {kind: bltnSym, builtin: _len},
467 bltnMake: {kind: bltnSym, builtin: _make},
468 bltnNew: {kind: bltnSym, builtin: _new},
469 bltnPanic: {kind: bltnSym, builtin: _panic},
470 bltnPrint: {kind: bltnSym, builtin: _print},
471 bltnPrintln: {kind: bltnSym, builtin: _println},
472 bltnReal: {kind: bltnSym, builtin: _real},
473 bltnRecover: {kind: bltnSym, builtin: _recover},
474 }}
475 return sc
476 }
477
478 // resizeFrame resizes the global frame of interpreter.
479 func (interp *Interpreter) resizeFrame() {
480 l := len(interp.universe.types)
481 b := len(interp.frame.data)
482 if l-b <= 0 {
483 return
484 }
485 data := make([]reflect.Value, l)
486 copy(data, interp.frame.data)
487 for j, t := range interp.universe.types[b:] {
488 data[b+j] = reflect.New(t).Elem()
489 }
490 interp.frame.data = data
491 }
492
493 // Eval evaluates Go code represented as a string. Eval returns the last result
494 // computed by the interpreter, and a non nil error in case of failure.
495 func (interp *Interpreter) Eval(src string) (res reflect.Value, err error) {
496 return interp.eval(src, "", true)
497 }
498
499 // EvalPath evaluates Go code located at path and returns the last result computed
500 // by the interpreter, and a non nil error in case of failure.
501 // The main function of the main package is executed if present.
502 func (interp *Interpreter) EvalPath(path string) (res reflect.Value, err error) {
503 path = filepath.ToSlash(path) // Ensure path is in Unix format. Since we work with fs.FS, we need to use Unix path.
504 if !isFile(interp.opt.filesystem, path) {
505 _, err := interp.importSrc(mainID, path, NoTest)
506 return res, err
507 }
508
509 b, err := fs.ReadFile(interp.filesystem, path)
510 if err != nil {
511 return res, err
512 }
513 return interp.eval(string(b), path, false)
514 }
515
516 // EvalPathWithContext evaluates Go code located at path and returns the last
517 // result computed by the interpreter, and a non nil error in case of failure.
518 // The main function of the main package is executed if present.
519 func (interp *Interpreter) EvalPathWithContext(ctx context.Context, path string) (res reflect.Value, err error) {
520 interp.mutex.Lock()
521 interp.done = make(chan struct{})
522 interp.cancelChan = !interp.opt.fastChan
523 interp.mutex.Unlock()
524
525 done := make(chan struct{})
526 go func() {
527 defer close(done)
528 res, err = interp.EvalPath(path)
529 }()
530
531 select {
532 case <-ctx.Done():
533 interp.stop()
534 return reflect.Value{}, ctx.Err()
535 case <-done:
536 }
537 return res, err
538 }
539
540 // EvalTest evaluates Go code located at path, including test files with "_test.go" suffix.
541 // A non nil error is returned in case of failure.
542 // The main function, test functions and benchmark functions are internally compiled but not
543 // executed. Test functions can be retrieved using the Symbol() method.
544 func (interp *Interpreter) EvalTest(path string) error {
545 _, err := interp.importSrc(mainID, path, Test)
546 return err
547 }
548
549 func isFile(filesystem fs.FS, path string) bool {
550 fi, err := fs.Stat(filesystem, path)
551 return err == nil && fi.Mode().IsRegular()
552 }
553
554 func (interp *Interpreter) eval(src, name string, inc bool) (res reflect.Value, err error) {
555 prog, err := interp.compileSrc(src, name, inc)
556 if err != nil {
557 return res, err
558 }
559
560 if interp.noRun {
561 return res, err
562 }
563
564 return interp.Execute(prog)
565 }
566
567 // EvalWithContext evaluates Go code represented as a string. It returns
568 // a map on current interpreted package exported symbols.
569 func (interp *Interpreter) EvalWithContext(ctx context.Context, src string) (reflect.Value, error) {
570 var v reflect.Value
571 var err error
572
573 interp.mutex.Lock()
574 interp.done = make(chan struct{})
575 interp.cancelChan = !interp.opt.fastChan
576 interp.mutex.Unlock()
577
578 done := make(chan struct{})
579 go func() {
580 defer func() {
581 if r := recover(); r != nil {
582 var pc [64]uintptr
583 n := runtime.Callers(1, pc[:])
584 err = Panic{Value: r, Callers: pc[:n], Stack: debug.Stack()}
585 }
586 close(done)
587 }()
588 v, err = interp.Eval(src)
589 }()
590
591 select {
592 case <-ctx.Done():
593 interp.stop()
594 return reflect.Value{}, ctx.Err()
595 case <-done:
596 }
597 return v, err
598 }
599
600 // stop sends a semaphore to all running frames and closes the chan
601 // operation short circuit channel. stop may only be called once per
602 // invocation of EvalWithContext.
603 func (interp *Interpreter) stop() {
604 atomic.AddUint64(&interp.id, 1)
605 close(interp.done)
606 }
607
608 func (interp *Interpreter) runid() uint64 { return atomic.LoadUint64(&interp.id) }
609
610 // ignoreScannerError returns true if the error from Go scanner can be safely ignored
611 // to let the caller grab one more line before retrying to parse its input.
612 func ignoreScannerError(e *scanner.Error, s string) bool {
613 msg := e.Msg
614 if strings.HasSuffix(msg, "found 'EOF'") {
615 return true
616 }
617 if msg == "raw string literal not terminated" {
618 return true
619 }
620 if strings.HasPrefix(msg, "expected operand, found '}'") && !strings.HasSuffix(s, "}") {
621 return true
622 }
623 return false
624 }
625
626 // ImportUsed automatically imports pre-compiled packages included by Use().
627 // This is mainly useful for REPLs, or single command lines. In case of an ambiguous default
628 // package name, for example "rand" for crypto/rand and math/rand, the package name is
629 // constructed by replacing the last "/" by a "_", producing crypto_rand and math_rand.
630 // ImportUsed should not be called more than once, and not after a first Eval, as it may
631 // rename packages.
632 func (interp *Interpreter) ImportUsed() {
633 sc := interp.universe
634 for k := range interp.binPkg {
635 // By construction, the package name is the last path element of the key.
636 name := path.Base(k)
637 if sym, ok := sc.sym[name]; ok {
638 // Handle collision by renaming old and new entries.
639 name2 := key2name(fixKey(sym.typ.path))
640 sc.sym[name2] = sym
641 if name2 != name {
642 delete(sc.sym, name)
643 }
644 name = key2name(fixKey(k))
645 }
646 sc.sym[name] = &symbol{kind: pkgSym, typ: &itype{cat: binPkgT, path: k, scope: sc}}
647 }
648 }
649
650 func key2name(name string) string {
651 return path.Join(name, DefaultSourceName)
652 }
653
654 func fixKey(k string) string {
655 i := strings.LastIndex(k, "/")
656 if i >= 0 {
657 k = k[:i] + "_" + k[i+1:]
658 }
659 return k
660 }
661
662 // REPL performs a Read-Eval-Print-Loop on input reader.
663 // Results are printed to the output writer of the Interpreter, provided as option
664 // at creation time. Errors are printed to the similarly defined errors writer.
665 // The last interpreter result value and error are returned.
666 func (interp *Interpreter) REPL() (reflect.Value, error) {
667 in, out, errs := interp.stdin, interp.stdout, interp.stderr
668 ctx, cancel := context.WithCancel(context.Background())
669 end := make(chan struct{}) // channel to terminate the REPL
670 sig := make(chan os.Signal, 1) // channel to trap interrupt signal (Ctrl-C)
671 lines := make(chan string) // channel to read REPL input lines
672 prompt := getPrompt(in, out) // prompt activated on tty like IO stream
673 s := bufio.NewScanner(in) // read input stream line by line
674 var v reflect.Value // result value from eval
675 var err error // error from eval
676 src := "" // source string to evaluate
677
678 signal.Notify(sig, os.Interrupt)
679 defer signal.Stop(sig)
680 prompt(v)
681
682 go func() {
683 defer close(end)
684 for s.Scan() {
685 lines <- s.Text()
686 }
687 if e := s.Err(); e != nil {
688 fmt.Fprintln(errs, e)
689 }
690 }()
691
692 go func() {
693 for {
694 select {
695 case <-sig:
696 cancel()
697 lines <- ""
698 case <-end:
699 return
700 }
701 }
702 }()
703
704 for {
705 var line string
706
707 select {
708 case <-end:
709 cancel()
710 return v, err
711 case line = <-lines:
712 src += line + "\n"
713 }
714
715 v, err = interp.EvalWithContext(ctx, src)
716 if err != nil {
717 switch e := err.(type) {
718 case scanner.ErrorList:
719 if len(e) > 0 && ignoreScannerError(e[0], line) {
720 continue
721 }
722 fmt.Fprintln(errs, strings.TrimPrefix(e[0].Error(), DefaultSourceName+":"))
723 case Panic:
724 fmt.Fprintln(errs, e.Value)
725 fmt.Fprintln(errs, string(e.Stack))
726 default:
727 fmt.Fprintln(errs, err)
728 }
729 }
730 if errors.Is(err, context.Canceled) {
731 ctx, cancel = context.WithCancel(context.Background())
732 }
733 src = ""
734 prompt(v)
735 }
736 }
737
738 func doPrompt(out io.Writer) func(v reflect.Value) {
739 return func(v reflect.Value) {
740 if v.IsValid() {
741 fmt.Fprintln(out, ":", v)
742 }
743 fmt.Fprint(out, "> ")
744 }
745 }
746
747 // getPrompt returns a function which prints a prompt only if input is a terminal.
748 func getPrompt(in io.Reader, out io.Writer) func(reflect.Value) {
749 forcePrompt, _ := strconv.ParseBool(os.Getenv("YAEGI_PROMPT"))
750 if forcePrompt {
751 return doPrompt(out)
752 }
753 s, ok := in.(interface{ Stat() (os.FileInfo, error) })
754 if !ok {
755 return func(reflect.Value) {}
756 }
757 stat, err := s.Stat()
758 if err == nil && stat.Mode()&os.ModeCharDevice != 0 {
759 return doPrompt(out)
760 }
761 return func(reflect.Value) {}
762 }