Skip to content

Commit

Permalink
Fix: correctly check error type of func return types
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Jan 21, 2023
1 parent 629453d commit b062494
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
13 changes: 13 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1646,6 +1646,19 @@ func TestFastCall(t *testing.T) {
assert.Equal(t, float64(8), out)
}

func TestRun_custom_func_returns_an_error_as_second_arg(t *testing.T) {
env := map[string]interface{}{
"semver": func(value string, cmp string) (bool, error) { return true, nil },
}

p, err := expr.Compile(`semver("1.2.3", "= 1.2.3")`, expr.Env(env))
assert.NoError(t, err)

out, err := expr.Run(p, env)
assert.NoError(t, err)
assert.Equal(t, true, out)
}

// Mock types

type mockEnv struct {
Expand Down
7 changes: 3 additions & 4 deletions vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ import (
"github.com/antonmedv/expr/vm/runtime"
)

var (
MemoryBudget int = 1e6
)
var MemoryBudget int = 1e6
var errorType = reflect.TypeOf((*error)(nil)).Elem()

func Run(program *Program, env interface{}) (interface{}, error) {
if program == nil {
Expand Down Expand Up @@ -302,7 +301,7 @@ func (vm *VM) Run(program *Program, env interface{}) (out interface{}, err error
}
}
out := fn.Call(in)
if len(out) == 2 && !runtime.IsNil(out[1]) {
if len(out) == 2 && out[1].Type() == errorType && !out[1].IsNil() {
panic(out[1].Interface().(error))
}
vm.push(out[0].Interface())
Expand Down

0 comments on commit b062494

Please sign in to comment.