Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run CompiledFunction in VM #372

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions script.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,13 @@ func (c *Compiled) Set(name string, value interface{}) error {
c.globals[idx] = obj
return nil
}

// Bytecode returns bytecode of this Compiled
func (c *Compiled) Bytecode() *Bytecode {
return c.bytecode
}

// Globals return globals in this Compiled
func (c *Compiled) Globals() []Object {
return c.globals
}
60 changes: 55 additions & 5 deletions vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,69 @@ func (v *VM) Abort() {
atomic.StoreInt64(&v.aborting, 1)
}

// constant wrapper function func(fn, ...args){ return fn(args...) }
var funcWrapper = &CompiledFunction{
Instructions: append(
MakeInstruction(parser.OpGetLocal, 0),
append(MakeInstruction(parser.OpGetLocal, 1),
append(MakeInstruction(parser.OpCall, 1, 1),
MakeInstruction(parser.OpReturn, 1)...)...)...,
),
NumLocals: 2,
NumParameters: 2,
VarArgs: true,
}

// RunCompiled run specified function in VM context
func (v *VM) RunCompiled(fn *CompiledFunction, args ...Object) (val Object, err error) {
v.stack = [StackSize]Object{}
sp := 0

if fn != nil { // run user supplied function
entry := &CompiledFunction{
Instructions: append(
MakeInstruction(parser.OpCall, 1+len(args), 0),
MakeInstruction(parser.OpSuspend)...,
),
}
v.stack[0] = funcWrapper
v.stack[1] = fn
for i, arg := range args {
v.stack[i+2] = arg
}
sp = 2 + len(args)
v.frames[0].fn = entry
}

v.resetState()
v.sp = sp

val = UndefinedValue
v.run()
if fn != nil && atomic.LoadInt64(&v.aborting) == 0 {
val = v.stack[v.sp-1]
}
atomic.StoreInt64(&v.aborting, 0)
err = v.handleError()
return
}

// Run starts the execution.
func (v *VM) Run() (err error) {
// reset VM states
_, err = v.RunCompiled(nil)
return
}

func (v *VM) resetState() {
v.sp = 0
v.curFrame = &(v.frames[0])
v.curInsts = v.curFrame.fn.Instructions
v.framesIndex = 1
v.ip = -1
v.allocs = v.maxAllocs + 1
}

v.run()
atomic.StoreInt64(&v.aborting, 0)
func (v *VM) handleError() (err error) {
err = v.err
if err != nil {
filePos := v.fileSet.Position(
Expand All @@ -89,9 +140,8 @@ func (v *VM) Run() (err error) {
v.curFrame.fn.SourcePos(v.curFrame.ip - 1))
err = fmt.Errorf("%w\n\tat %s", err, filePos)
}
return err
}
return nil
return
}

func (v *VM) run() {
Expand Down
54 changes: 54 additions & 0 deletions vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3625,6 +3625,60 @@ func TestSpread(t *testing.T) {
"Runtime Error: wrong number of arguments: want=3, got=2")
}

func TestRunCompiled(t *testing.T) {
s := tengo.NewScript([]byte(`fnMap := {"fun1": func(a) { return a * 2 }}`))
c, err := s.Run()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s.Compile() should do here

require.NoError(t, err)

cFn := c.Get("fnMap").Map()["fun1"].(*tengo.CompiledFunction)

globals := make([]tengo.Object, tengo.GlobalsSize)
vm := tengo.NewVM(c.Bytecode(), globals, -1)
require.NotNil(t, vm)

res, err := vm.RunCompiled(cFn, &tengo.Int{Value: 12})
require.NoError(t, err)
require.NotNil(t, res)
require.Equal(t, res, &tengo.Int{Value: 24})
}

func TestRunCompiledWithModules(t *testing.T) {
mods := tengo.NewModuleMap()
mods.AddSourceModule("mod2", []byte(`export func() { return 5 }`))
mods.AddSourceModule("mod1", []byte(`mod2 := import("mod2"); export func() { return mod2() * 3 }`))

s := tengo.NewScript([]byte(`mod1 := import("mod1"); fnMap := {"fun1": func(a) { return a * 2 + mod1() }}`))
s.SetImports(mods)

c, err := s.Run()
require.NoError(t, err)

cFn := c.Get("fnMap").Map()["fun1"].(*tengo.CompiledFunction)

var testCases [][]int64
for i := 0; i < 1000; i++ {
testCases = append(testCases, []int64{int64(i), int64(2*i + 15)})
}

results := make(chan bool, 1000)

for _, testCase := range testCases {
go func(pair []int64) {
vm := tengo.NewVM(c.Bytecode(), c.Globals(), -1)
require.NotNil(t, vm)
res, err := vm.RunCompiled(cFn, &tengo.Int{Value: pair[0]})
require.NoError(t, err)
require.NotNil(t, res)
require.Equal(t, &tengo.Int{Value: pair[1]}, res)
results <- true
}(testCase)
}

for i := 0; i < 1000; i++ {
require.True(t, <-results)
}
}

func expectRun(
t *testing.T,
input string,
Expand Down