-
Notifications
You must be signed in to change notification settings - Fork 28
/
executor.go
287 lines (258 loc) · 6.64 KB
/
executor.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
package slang
import (
"fmt"
"go/scanner"
"go/token"
"io"
"os"
"reflect"
"sort"
"strings"
"v.io/v23/context"
)
// Script represents the execution of a single script.
type Script struct {
stdout io.Writer
envvars map[string]string
ctx *context.T
symbols *symbolTable
invocations []invocation
}
func (scr *Script) RegisterConst(name string, value interface{}) {
if scr.symbols == nil {
scr.symbols = newSymbolTable()
}
rv := reflect.ValueOf(value)
rt := rv.Type()
scr.symbols.constants[name] = true
scr.symbols.types[name] = rt
scr.symbols.values[name] = rv
}
// SetEnv sets an environment variable that will be available to the
// script that's preferred to any value in the processes environment.
func (scr *Script) SetEnv(name, value string) {
if scr.envvars == nil {
scr.envvars = map[string]string{}
}
scr.envvars[name] = value
}
// String returns a string representation of the compiled script
// and any variables defined during its execution.
func (scr *Script) String() string {
out := &strings.Builder{}
scr.formatEnv(out)
scr.formatCompiledState(out)
scr.symbols.formatValues(out)
return out.String()
}
// Variables returns a copy of the currently defined variables.
func (scr *Script) Variables() map[string]interface{} {
vals := make(map[string]interface{}, len(scr.symbols.values))
for k, v := range scr.symbols.values {
vals[k] = v.Interface()
}
return vals
}
// ExecuteBytes will parse, compile and execute the supplied script.
func (scr *Script) ExecuteBytes(ctx *context.T, src []byte) error {
stmts, err := parseBytes(src)
if err != nil {
return err
}
return scr.compileAndRun(ctx, stmts)
}
// ExecuteFile will parse, compile and execute the script contained in
// the specified file.
func (scr *Script) ExecuteFile(ctx *context.T, filename string) error {
stmts, err := parseFile(filename)
if err != nil {
return err
}
return scr.compileAndRun(ctx, stmts)
}
func (scr *Script) compileAndRun(ctx *context.T, stmts statements) error {
if err := scr.compile(stmts); err != nil {
return err
}
scr.ctx = ctx
if scr.stdout == nil {
scr.stdout = os.Stdout
}
return scr.run()
}
// value is the interface implemented by either runtime variables
// or literals.
type value interface {
value(st *symbolTable) reflect.Value
varOrLiteral() string
ellipsis() bool
}
// symbolTable tracks the type of all compile-time defined
// variables and the values of these variables at runtime.
type symbolTable struct {
constants map[string]bool
types map[string]reflect.Type
values map[string]reflect.Value
}
func newSymbolTable() *symbolTable {
return &symbolTable{
constants: map[string]bool{},
types: map[string]reflect.Type{},
values: map[string]reflect.Value{},
}
}
// invocation is the compiled form of a single statement - i.e.
// function invocation.
type invocation struct {
pos token.Position
verb verb
args []value
results []value
assignment bool
}
func (scr *Script) formatEnv(out *strings.Builder) {
names := make([]string, 0, len(scr.envvars))
for k := range scr.envvars {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
fmt.Fprintf(out, "$%v=%v\n", k, scr.envvars[k])
}
}
func (st *symbolTable) formatTypes(out *strings.Builder) {
names := make([]string, 0, len(st.types))
for k := range st.types {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
fmt.Fprintf(out, "%v: %v\n", k, st.types[k])
}
}
func (st *symbolTable) formatValues(out *strings.Builder) {
names := make([]string, 0, len(st.values))
for k := range st.values {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
v := st.values[k]
fmt.Fprintf(out, "%v: %v: %v\n", k, v.Type(), fmt.Sprintf("%v", v.Interface()))
}
}
// compiledState returns a string representation of the compiled state.
func (scr *Script) formatCompiledState(out *strings.Builder) {
scr.symbols.formatTypes(out)
scr.symbols.formatValues(out)
for _, inv := range scr.invocations {
inv.format(out)
out.WriteRune('\n')
}
}
// runtimeState returns a string representation of the current
// execution state.
func (scr *Script) runtimeState() string {
out := &strings.Builder{}
scr.symbols.formatValues(out)
return out.String()
}
// format the invocation into a readable form.
func (inv invocation) format(out *strings.Builder) {
out.WriteString(inv.pos.String())
out.WriteString(": ")
for i, r := range inv.results {
out.WriteString(r.varOrLiteral())
if i < len(inv.results)-1 {
out.WriteString(", ")
}
}
if len(inv.results) > 0 {
if inv.assignment {
out.WriteString(" = ")
} else {
out.WriteString(" := ")
}
}
fmt.Fprintf(out, "%s(", inv.verb.name)
for i, a := range inv.args {
out.WriteString(a.varOrLiteral())
if a.ellipsis() {
out.WriteString("...")
}
if i < len(inv.args)-1 {
out.WriteString(", ")
}
}
out.WriteRune(')')
out.WriteString(" :: ")
out.WriteString(inv.verb.String())
}
type literalValue reflect.Value
func (lv literalValue) value(*symbolTable) reflect.Value {
return reflect.Value(lv)
}
func (lv literalValue) varOrLiteral() string {
rv := reflect.Value(lv)
if rv.Type().Kind() == reflect.String {
return fmt.Sprintf("%q", rv.Interface())
}
return fmt.Sprintf("%v", rv.Interface())
}
func (lv literalValue) ellipsis() bool {
return false
}
type variableValue struct {
name string
hasEllipsis bool
}
func (rv variableValue) value(st *symbolTable) reflect.Value {
v, ok := st.values[rv.name]
if !ok {
panic(fmt.Sprintf("variable %v has not been initialized", rv))
}
return v
}
func (rv variableValue) varOrLiteral() string {
return rv.name
}
func (rv variableValue) ellipsis() bool {
return rv.hasEllipsis
}
func (scr *Script) run() error {
errs := scanner.ErrorList{}
rt := reflect.ValueOf(scr)
for _, inv := range scr.invocations {
args := make([]reflect.Value, len(inv.args)+1)
args[0] = rt
useCallSlice := false
for i, arg := range inv.args {
args[i+1] = arg.value(scr.symbols)
if arg.ellipsis() {
if args[i+1].Type().Kind() == reflect.Slice {
useCallSlice = true
}
}
}
var results []reflect.Value
if useCallSlice {
results = inv.verb.implementation.CallSlice(args)
} else {
results = inv.verb.implementation.Call(args)
}
if len(results) < 1 {
panic("internal error: unexpected number of results")
}
if ierr := results[len(results)-1].Interface(); ierr != nil {
errs.Add(inv.pos, fmt.Sprintf("%s: %s", inv.verb.name, ierr.(error).Error()))
return errs.Err()
}
if len(results) == 1 {
continue
}
for i, v := range results[:len(results)-1] {
scr.symbols.values[inv.results[i].varOrLiteral()] = v
}
}
return nil
}