-
Notifications
You must be signed in to change notification settings - Fork 154
/
compiler.go
427 lines (402 loc) · 11.3 KB
/
compiler.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
package compiler
import (
"fmt"
"github.com/influxdata/flux"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
"github.com/pkg/errors"
)
func Compile(f *semantic.FunctionExpression, in semantic.Type, builtins Scope) (Func, error) {
if in.Nature() != semantic.Object {
return nil, errors.New("function input must be an object")
}
declarations := externAssignments(builtins)
extern := &semantic.Extern{
Assignments: declarations,
Block: &semantic.ExternBlock{Node: f},
}
typeSol, err := semantic.InferTypes(extern, flux.StdLib())
if err != nil {
return nil, err
}
pt, err := typeSol.PolyTypeOf(f)
if err != nil {
return nil, err
}
props := in.Properties()
parameters := make(map[string]semantic.PolyType, len(props))
for k, p := range props {
parameters[k] = p.PolyType()
}
fpt := semantic.NewFunctionPolyType(semantic.FunctionPolySignature{
Parameters: parameters,
Return: typeSol.Fresh(),
})
if err := typeSol.AddConstraint(pt, fpt); err != nil {
return nil, err
}
fnType, err := typeSol.TypeOf(f)
if err != nil {
return nil, errors.Wrap(err, "cannot compile polymorphic function")
}
root, err := compile(f.Block.Body, typeSol, builtins, make(map[string]*semantic.FunctionExpression))
if err != nil {
return nil, err
}
return compiledFn{
root: root,
fnType: fnType,
inputScope: make(Scope),
}, nil
}
// monoType ignores any errors when reading the type of a node.
// This is safe becase we already validated that the function type is a mono type.
func monoType(t semantic.Type, err error) semantic.Type {
return t
}
// compile recursively compiles semantic nodes into evaluators.
func compile(n semantic.Node, typeSol semantic.TypeSolution, builtIns Scope, funcExprs map[string]*semantic.FunctionExpression) (Evaluator, error) {
switch n := n.(type) {
case *semantic.Block:
body := make([]Evaluator, len(n.Body))
for i, s := range n.Body {
node, err := compile(s, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
body[i] = node
}
return &blockEvaluator{
t: monoType(typeSol.TypeOf(n.ReturnStatement().Argument)),
body: body,
}, nil
case *semantic.ExpressionStatement:
return nil, errors.New("statement does nothing, side effects are not supported by the compiler")
case *semantic.ReturnStatement:
node, err := compile(n.Argument, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return returnEvaluator{
Evaluator: node,
}, nil
case *semantic.NativeVariableAssignment:
if fe, ok := n.Init.(*semantic.FunctionExpression); ok {
funcExprs[n.Identifier.Name] = fe
return &noopEvaluator{}, nil
}
node, err := compile(n.Init, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &declarationEvaluator{
t: monoType(typeSol.TypeOf(n.Init)),
id: n.Identifier.Name,
init: node,
}, nil
case *semantic.ObjectExpression:
properties := make(map[string]Evaluator, len(n.Properties))
propertyTypes := make(map[string]semantic.Type, len(n.Properties))
for _, p := range n.Properties {
node, err := compile(p.Value, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
properties[p.Key.Key()] = node
propertyTypes[p.Key.Key()] = node.Type()
}
return &objEvaluator{
t: semantic.NewObjectType(propertyTypes),
properties: properties,
}, nil
case *semantic.ArrayExpression:
elements := make([]Evaluator, len(n.Elements))
if len(n.Elements) == 0 {
return &arrayEvaluator{
t: semantic.EmptyArrayType,
array: nil,
}, nil
}
for i, e := range n.Elements {
node, err := compile(e, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
elements[i] = node
}
return &arrayEvaluator{
t: semantic.NewArrayType(elements[0].Type()),
array: elements,
}, nil
case *semantic.IdentifierExpression:
if v, ok := builtIns[n.Name]; ok {
//Resolve any built in identifiers now
return &valueEvaluator{
value: v,
}, nil
}
// Create type instance of the function
if fe, ok := funcExprs[n.Name]; ok {
it, err := typeSol.PolyTypeOf(n)
if err != nil {
return nil, err
}
ft, err := typeSol.PolyTypeOf(fe)
if err != nil {
return nil, err
}
typeSol := typeSol.FreshSolution()
// Add constraint on the identifier type and the function type.
// This way all type variables in the body of the function will know their monotype.
err = typeSol.AddConstraint(it, ft)
if err != nil {
return nil, err
}
return compile(fe, typeSol, builtIns, funcExprs)
}
return &identifierEvaluator{
t: monoType(typeSol.TypeOf(n)),
name: n.Name,
}, nil
case *semantic.MemberExpression:
object, err := compile(n.Object, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &memberEvaluator{
t: monoType(typeSol.TypeOf(n)),
object: object,
property: n.Property,
}, nil
case *semantic.IndexExpression:
arr, err := compile(n.Array, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
idx, err := compile(n.Index, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &arrayIndexEvaluator{
t: monoType(typeSol.TypeOf(n)),
array: arr,
index: idx,
}, nil
case *semantic.BooleanLiteral:
return &booleanEvaluator{
t: monoType(typeSol.TypeOf(n)),
b: n.Value,
}, nil
case *semantic.IntegerLiteral:
return &integerEvaluator{
t: monoType(typeSol.TypeOf(n)),
i: n.Value,
}, nil
case *semantic.FloatLiteral:
return &floatEvaluator{
t: monoType(typeSol.TypeOf(n)),
f: n.Value,
}, nil
case *semantic.StringLiteral:
return &stringEvaluator{
t: monoType(typeSol.TypeOf(n)),
s: n.Value,
}, nil
case *semantic.RegexpLiteral:
return ®expEvaluator{
t: monoType(typeSol.TypeOf(n)),
r: n.Value,
}, nil
case *semantic.DateTimeLiteral:
return &timeEvaluator{
t: monoType(typeSol.TypeOf(n)),
time: values.ConvertTime(n.Value),
}, nil
case *semantic.DurationLiteral:
return &durationEvaluator{
t: monoType(typeSol.TypeOf(n)),
duration: values.Duration(n.Value),
}, nil
case *semantic.UnaryExpression:
node, err := compile(n.Argument, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &unaryEvaluator{
t: monoType(typeSol.TypeOf(n)),
node: node,
}, nil
case *semantic.LogicalExpression:
l, err := compile(n.Left, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
r, err := compile(n.Right, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &logicalEvaluator{
t: monoType(typeSol.TypeOf(n)),
operator: n.Operator,
left: l,
right: r,
}, nil
case *semantic.BinaryExpression:
l, err := compile(n.Left, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
lt := l.Type()
r, err := compile(n.Right, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
rt := r.Type()
f, err := values.LookupBinaryFunction(values.BinaryFuncSignature{
Operator: n.Operator,
Left: lt,
Right: rt,
})
if err != nil {
return nil, err
}
return &binaryEvaluator{
t: monoType(typeSol.TypeOf(n)),
left: l,
right: r,
f: f,
}, nil
case *semantic.CallExpression:
args, err := compile(n.Arguments, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
callee, err := compile(n.Callee, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
return &callEvaluator{
t: monoType(typeSol.TypeOf(n)),
callee: callee,
args: args,
}, nil
case *semantic.FunctionExpression:
fnType := monoType(typeSol.TypeOf(n))
body, err := compile(n.Block.Body, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
sig := fnType.FunctionSignature()
params := make([]functionParam, 0, len(sig.Parameters))
for k, pt := range sig.Parameters {
param := functionParam{
Key: k,
Type: pt,
}
if n.Defaults != nil {
// Search for default value
for _, d := range n.Defaults.Properties {
if d.Key.Key() == k {
d, err := compile(d.Value, typeSol, builtIns, funcExprs)
if err != nil {
return nil, err
}
param.Default = d
break
}
}
}
params = append(params, param)
}
return &functionEvaluator{
t: fnType,
params: params,
body: body,
}, nil
default:
return nil, fmt.Errorf("unknown semantic node of type %T", n)
}
}
// CompilationCache caches compilation results based on the type of the function.
type CompilationCache struct {
fn *semantic.FunctionExpression
scope Scope
compiled map[semantic.Type]funcErr
}
func NewCompilationCache(fn *semantic.FunctionExpression, scope Scope) *CompilationCache {
return &CompilationCache{
fn: fn,
scope: scope,
compiled: make(map[semantic.Type]funcErr),
}
}
// Compile returns a compiled function based on the provided type.
// The result will be cached for subsequent calls.
func (c *CompilationCache) Compile(in semantic.Type) (Func, error) {
f, ok := c.compiled[in]
if ok {
return f.F, f.Err
}
fun, err := Compile(c.fn, in, c.scope)
c.compiled[in] = funcErr{
F: fun,
Err: err,
}
return fun, err
}
type funcErr struct {
F Func
Err error
}
// Utility function for compiling an `fn` parameter for rename or drop/keep. In addition
// to the function expression, it takes two types to verify the result against:
// a single argument type, and a single return type.
func CompileFnParam(fn *semantic.FunctionExpression, paramType, returnType semantic.Type) (Func, string, error) {
scope := flux.BuiltIns()
compileCache := NewCompilationCache(fn, scope)
if fn.Block.Parameters != nil && len(fn.Block.Parameters.List) != 1 {
return nil, "", errors.New("function should only have a single parameter")
}
paramName := fn.Block.Parameters.List[0].Key.Name
compiled, err := compileCache.Compile(semantic.NewObjectType(map[string]semantic.Type{
paramName: paramType,
}))
if err != nil {
return nil, "", err
}
if compiled.Type() != returnType {
return nil, "", fmt.Errorf("provided function does not evaluate to type %s", returnType.Nature())
}
return compiled, paramName, nil
}
func CompileReduceFn(fn *semantic.FunctionExpression, paramType semantic.Type) (Func, []string, error) {
scope := flux.BuiltIns()
compileCache := NewCompilationCache(fn, scope)
if len(fn.Block.Parameters.List) != 2 {
return nil, nil, errors.New("function should only have a single parameter")
}
paramList := fn.Block.Parameters.List
paramNames := []string{paramList[0].Key.Name, paramList[1].Key.Name}
compiled, err := compileCache.Compile(semantic.NewObjectType(map[string]semantic.Type{
paramNames[0]: paramType,
paramNames[1]: paramType,
}))
if err != nil {
return nil, nil, err
}
if compiled.Type() != paramType {
return nil, nil, fmt.Errorf("provided function does not evaluate to type %s", paramType.Nature())
}
return compiled, paramNames, nil
}
// externAssignments produces a list of external declarations from a scope
func externAssignments(scope Scope) []*semantic.ExternalVariableAssignment {
declarations := make([]*semantic.ExternalVariableAssignment, 0, len(scope))
for k, v := range scope {
declarations = append(declarations, &semantic.ExternalVariableAssignment{
Identifier: &semantic.Identifier{Name: k},
ExternType: v.PolyType(),
})
}
return declarations
}