forked from elves/elvish
/
eval.go
247 lines (216 loc) · 6.31 KB
/
eval.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
// Package eval handles evaluation of parsed Elvish code and provides runtime
// facilities.
package eval
import (
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
"syscall"
"unicode/utf8"
"github.com/elves/elvish/daemon"
"github.com/elves/elvish/eval/bundled"
"github.com/elves/elvish/eval/types"
"github.com/elves/elvish/eval/vartypes"
"github.com/elves/elvish/parse"
"github.com/elves/elvish/sys"
"github.com/elves/elvish/util"
"github.com/xiaq/persistent/vector"
)
var logger = util.GetLogger("[eval] ")
const (
// FnSuffix is the suffix for the variable names of functions. Defining a
// function "foo" is equivalent to setting a variable named "foo~", and vice
// versa.
FnSuffix = "~"
// NsSuffix is the suffix for the variable names of namespaces. Defining a
// namespace foo is equivalent to setting a variable named "foo:", and vice
// versa.
NsSuffix = ":"
)
const (
defaultValueOutIndicator = "▶ "
initIndent = types.NoPretty
)
// Evaler is used to evaluate elvish sources. It maintains runtime context
// shared among all evalCtx instances.
type Evaler struct {
evalerScopes
evalerPorts
DaemonClient *daemon.Client
modules map[string]Ns
// bundled modules
bundled map[string]string
Editor Editor
libDir string
intCh chan struct{}
}
type evalerScopes struct {
Global Ns
Builtin Ns
}
// NewEvaler creates a new Evaler.
func NewEvaler() *Evaler {
valueOutIndicator := defaultValueOutIndicator
builtin := builtinNs.Clone()
builtin["value-out-indicator"] = NewVariableFromPtr(&valueOutIndicator)
ev := &Evaler{
evalerScopes: evalerScopes{
Global: make(Ns),
Builtin: builtinNs,
},
evalerPorts: newEvalerPorts(
os.Stdin, os.Stdout, os.Stderr, &valueOutIndicator),
modules: map[string]Ns{
"builtin": builtin,
},
bundled: bundled.Get(),
Editor: nil,
intCh: nil,
}
return ev
}
// Close releases resources allocated when creating this Evaler.
func (ev *Evaler) Close() {
ev.evalerPorts.close()
}
// InstallDaemonClient installs a daemon client to the Evaler.
func (ev *Evaler) InstallDaemonClient(client *daemon.Client) {
ev.DaemonClient = client
// XXX This is really brittle
ev.Builtin["pwd"] = PwdVariable{client}
}
// InstallModule installs a module to the Evaler so that it can be used with
// "use $name" from script.
func (ev *Evaler) InstallModule(name string, mod Ns) {
ev.modules[name] = mod
}
// InstallBundled installs a bundled module to the Evaler.
func (ev *Evaler) InstallBundled(name, src string) {
ev.bundled[name] = src
}
// SetArgs sets the $args builtin variable.
func (ev *Evaler) SetArgs(args []string) {
v := vector.Empty
for _, arg := range args {
v = v.Cons(arg)
}
ev.Builtin["args"] = vartypes.NewRo(v)
}
// SetLibDir sets the library directory, in which external modules are to be
// found.
func (ev *Evaler) SetLibDir(libDir string) {
ev.libDir = libDir
}
func searchPaths() []string {
return strings.Split(os.Getenv("PATH"), ":")
}
// growPorts makes the size of ec.ports at least n, adding nil's if necessary.
func (ec *Frame) growPorts(n int) {
if len(ec.ports) >= n {
return
}
ports := ec.ports
ec.ports = make([]*Port, n)
copy(ec.ports, ports)
}
// eval evaluates a chunk node n. The supplied name and text are used in
// diagnostic messages.
func (ev *Evaler) eval(op Op, ports []*Port, src *Source) error {
ec := NewTopFrame(ev, src, ports)
return ec.PEval(op)
}
// Eval sets up the Evaler with standard ports and evaluates an Op. The supplied
// name and text are used in diagnostic messages.
func (ev *Evaler) Eval(op Op, src *Source) error {
return ev.EvalWithPorts(ev.ports[:], op, src)
}
// EvalWithPorts sets up the Evaler with the given ports and evaluates an Op.
// The supplied name and text are used in diagnostic messages.
func (ev *Evaler) EvalWithPorts(ports []*Port, op Op, src *Source) error {
// Ignore TTOU.
//
// When a subprocess in its own process group puts itself in the foreground,
// Elvish will be put in the background. When the code finishes execution,
// Elvish will attempt to move itself back to the foreground by calling
// tcsetpgrp. However, whenever a background process calls tcsetpgrp (or
// otherwise attempts to modify the terminal configuration), TTOU will be
// sent, whose default handler is to stop the process. Or, if the process
// lives in an orphaned process group (which is often the case for Elvish),
// the call will outright fail. Therefore, for Elvish to be able to move
// itself back to the foreground later, we need to ignore TTOU now.
ignoreTTOU()
defer unignoreTTOU()
stopSigGoroutine := make(chan struct{})
sigGoRoutineDone := make(chan struct{})
// Set up intCh.
ev.intCh = make(chan struct{})
sigCh := make(chan os.Signal)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGQUIT)
go func() {
closedIntCh := false
loop:
for {
select {
case <-sigCh:
if !closedIntCh {
close(ev.intCh)
closedIntCh = true
}
case <-stopSigGoroutine:
break loop
}
}
ev.intCh = nil
signal.Stop(sigCh)
close(sigGoRoutineDone)
}()
err := ev.eval(op, ports, src)
close(stopSigGoroutine)
<-sigGoRoutineDone
// Put myself in foreground, in case some command has put me in background.
// XXX Should probably use fd of /dev/tty instead of 0.
if sys.IsATTY(os.Stdin) {
err := putSelfInFg()
if err != nil {
fmt.Println("failed to put myself in foreground:", err)
}
}
return err
}
// Compile compiles elvish code in the global scope. If the error is not nil, it
// always has type CompilationError.
func (ev *Evaler) Compile(n *parse.Chunk, src *Source) (Op, error) {
return compile(ev.Builtin.static(), ev.Global.static(), n, src)
}
// SourceText evaluates a chunk of elvish source.
func (ev *Evaler) SourceText(src *Source) error {
n, err := parse.Parse(src.name, src.code)
if err != nil {
return err
}
op, err := ev.Compile(n, src)
if err != nil {
return err
}
return ev.Eval(op, src)
}
func readFileUTF8(fname string) (string, error) {
bytes, err := ioutil.ReadFile(fname)
if err != nil {
return "", err
}
if !utf8.Valid(bytes) {
return "", fmt.Errorf("%s: source is not valid UTF-8", fname)
}
return string(bytes), nil
}
// Source evaluates the content of a file.
func (ev *Evaler) Source(name, path string) error {
code, err := readFileUTF8(path)
if err != nil {
return err
}
return ev.SourceText(NewScriptSource(name, path, code))
}