-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpret.go
80 lines (64 loc) · 1.51 KB
/
interpret.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
package interpret
import (
"github.com/grafana/sobek"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
)
func init() {
modules.Register("k6/x/interpret", New())
}
type (
// RootModule is the global module instance that will create module
// instances for each VU.
RootModule struct{}
// ModuleInstance represents an instance of the JS module.
ModuleInstance struct {
// vu provides methods for accessing internal k6 objects for a VU
vu modules.VU
}
)
var (
_ modules.Module = &RootModule{}
_ modules.Instance = &ModuleInstance{}
)
func New() *RootModule {
return &RootModule{}
}
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
return &ModuleInstance{
vu: vu,
}
}
type Interpret struct {
vu modules.VU
}
func (r *Interpret) Run(src string, args ...interface{}) interface{} {
i := interp.New(interp.Options{})
i.Use(stdlib.Symbols)
_, err := i.Eval(src)
if err != nil {
common.Throw(r.vu.Runtime(), err)
}
v, err := i.Eval("interpret.Run")
if err != nil {
common.Throw(r.vu.Runtime(), err)
}
run := v.Interface().(func(...interface{}) interface{})
return run(args...)
}
func (mi *ModuleInstance) Exports() modules.Exports {
return modules.Exports{
Named: map[string]interface{}{
"Interpret": mi.newInterpret,
},
}
}
func (mi *ModuleInstance) newInterpret(c sobek.ConstructorCall) *sobek.Object {
rt := mi.vu.Runtime()
obj := &Interpret{
vu: mi.vu,
}
return rt.ToValue(obj).ToObject(rt)
}