/
compile.go
70 lines (59 loc) · 1.55 KB
/
compile.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
package executetest
import (
"context"
"fmt"
"testing"
"github.com/influxdata/flux/interpreter"
"github.com/influxdata/flux/runtime"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
)
var (
prelude values.Scope
stdlib interpreter.Importer
)
// FunctionExpression will take a function expression as a string
// and return the *semantic.FunctionExpression.
//
// This will cause a fatal error in the test on failure.
func FunctionExpression(t testing.TB, source string, args ...interface{}) *semantic.FunctionExpression {
t.Helper()
if len(args) > 0 {
source = fmt.Sprintf(source, args...)
}
if stdlib == nil {
stdlib = runtime.StdLib()
}
if prelude == nil {
prelude = values.NewScope()
for _, path := range runtime.PreludeList {
p, err := stdlib.ImportPackageObject(path)
if err != nil {
t.Fatalf("error importing prelude package %q: %s", path, err)
}
p.Range(prelude.Set)
}
}
ctx := context.Background()
pkg, err := runtime.AnalyzeSource(ctx, source)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
// Interpret and resolve the function which will replace
// variables with their values (notably identifiers "true"
// and "false" will be replaced with boolean literals)
itrp := interpreter.NewInterpreter(nil, nil)
se, err := itrp.Eval(ctx, pkg, prelude, stdlib)
if err != nil {
t.Fatal(err)
}
if len(se) != 1 {
t.Fatal("expected just one side effect")
}
f := se[0].Value.(values.Function)
rf, err := interpreter.ResolveFunction(f)
if err != nil {
t.Fatal(err)
}
return rf.Fn
}