aboutsummaryrefslogtreecommitdiff
path: root/repl/repl.go
blob: 2448192afe8f14a12fa571615fed1e8a9e6fc59e (plain)
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
// The repl package provides a read/eval/print loop for Starlark.
//
// It supports readline-style command editing,
// and interrupts through Control-C.
//
// If an input line can be parsed as an expression,
// the REPL parses and evaluates it and prints its result.
// Otherwise the REPL reads lines until a blank line,
// then tries again to parse the multi-line input as an
// expression. If the input still cannot be parsed as an expression,
// the REPL parses and executes it as a file (a list of statements),
// for side effects.
package repl // import "go.starlark.net/repl"

// TODO(adonovan):
//
// - Unparenthesized tuples are not parsed as a single expression:
//     >>> (1, 2)
//     (1, 2)
//     >>> 1, 2
//     ...
//     >>>
//   This is not necessarily a bug.

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"os/signal"
	"strings"

	"github.com/chzyer/readline"
	"go.starlark.net/starlark"
	"go.starlark.net/syntax"
)

var interrupted = make(chan os.Signal, 1)

// REPL executes a read, eval, print loop.
//
// Before evaluating each expression, it sets the Starlark thread local
// variable named "context" to a context.Context that is cancelled by a
// SIGINT (Control-C). Client-supplied global functions may use this
// context to make long-running operations interruptable.
//
func REPL(thread *starlark.Thread, globals starlark.StringDict) {
	signal.Notify(interrupted, os.Interrupt)
	defer signal.Stop(interrupted)

	rl, err := readline.New(">>> ")
	if err != nil {
		PrintError(err)
		return
	}
	defer rl.Close()
	for {
		if err := rep(rl, thread, globals); err != nil {
			if err == readline.ErrInterrupt {
				fmt.Println(err)
				continue
			}
			break
		}
	}
	fmt.Println()
}

// rep reads, evaluates, and prints one item.
//
// It returns an error (possibly readline.ErrInterrupt)
// only if readline failed. Starlark errors are printed.
func rep(rl *readline.Instance, thread *starlark.Thread, globals starlark.StringDict) error {
	// Each item gets its own context,
	// which is cancelled by a SIGINT.
	//
	// Note: during Readline calls, Control-C causes Readline to return
	// ErrInterrupt but does not generate a SIGINT.
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		select {
		case <-interrupted:
			cancel()
		case <-ctx.Done():
		}
	}()

	thread.SetLocal("context", ctx)

	rl.SetPrompt(">>> ")
	line, err := rl.Readline()
	if err != nil {
		return err // may be ErrInterrupt
	}

	if l := strings.TrimSpace(line); l == "" || l[0] == '#' {
		return nil // blank or comment
	}

	// If the line contains a well-formed expression, evaluate it.
	if _, err := syntax.ParseExpr("<stdin>", line, 0); err == nil {
		if v, err := starlark.Eval(thread, "<stdin>", line, globals); err != nil {
			PrintError(err)
		} else if v != starlark.None {
			fmt.Println(v)
		}
		return nil
	}

	// If the input so far is a single load or assignment statement,
	// execute it without waiting for a blank line.
	if f, err := syntax.Parse("<stdin>", line, 0); err == nil && len(f.Stmts) == 1 {
		switch f.Stmts[0].(type) {
		case *syntax.AssignStmt, *syntax.LoadStmt:
			// Execute it as a file.
			if err := execFileNoFreeze(thread, line, globals); err != nil {
				PrintError(err)
			}
			return nil
		}
	}

	// Otherwise assume it is the first of several
	// comprising a file, followed by a blank line.
	var buf bytes.Buffer
	fmt.Fprintln(&buf, line)
	for {
		rl.SetPrompt("... ")
		line, err := rl.Readline()
		if err != nil {
			return err // may be ErrInterrupt
		}
		if l := strings.TrimSpace(line); l == "" {
			break // blank
		}
		fmt.Fprintln(&buf, line)
	}
	text := buf.Bytes()

	// Try parsing it once more as an expression,
	// such as a call spread over several lines:
	//   f(
	//     1,
	//     2
	//   )
	if _, err := syntax.ParseExpr("<stdin>", text, 0); err == nil {
		if v, err := starlark.Eval(thread, "<stdin>", text, globals); err != nil {
			PrintError(err)
		} else if v != starlark.None {
			fmt.Println(v)
		}
		return nil
	}

	// Execute it as a file.
	if err := execFileNoFreeze(thread, text, globals); err != nil {
		PrintError(err)
	}

	return nil
}

// execFileNoFreeze is starlark.ExecFile without globals.Freeze().
func execFileNoFreeze(thread *starlark.Thread, src interface{}, globals starlark.StringDict) error {
	_, prog, err := starlark.SourceProgram("<stdin>", src, globals.Has)
	if err != nil {
		return err
	}

	res, err := prog.Init(thread, globals)

	// The global names from the previous call become
	// the predeclared names of this call.

	// Copy globals back to the caller's map.
	// If execution failed, some globals may be undefined.
	for k, v := range res {
		globals[k] = v
	}

	return err
}

// PrintError prints the error to stderr,
// or its backtrace if it is a Starlark evaluation error.
func PrintError(err error) {
	if evalErr, ok := err.(*starlark.EvalError); ok {
		fmt.Fprintln(os.Stderr, evalErr.Backtrace())
	} else {
		fmt.Fprintln(os.Stderr, err)
	}
}

// MakeLoad returns a simple sequential implementation of module loading
// suitable for use in the REPL.
// Each function returned by MakeLoad accesses a distinct private cache.
func MakeLoad() func(thread *starlark.Thread, module string) (starlark.StringDict, error) {
	type entry struct {
		globals starlark.StringDict
		err     error
	}

	var cache = make(map[string]*entry)

	return func(thread *starlark.Thread, module string) (starlark.StringDict, error) {
		e, ok := cache[module]
		if e == nil {
			if ok {
				// request for package whose loading is in progress
				return nil, fmt.Errorf("cycle in load graph")
			}

			// Add a placeholder to indicate "load in progress".
			cache[module] = nil

			// Load it.
			thread := &starlark.Thread{Load: thread.Load}
			globals, err := starlark.ExecFile(thread, module, nil, nil)
			e = &entry{globals, err}

			// Update the cache.
			cache[module] = e
		}
		return e.globals, e.err
	}
}