Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(vm): handle nil arguments in variadic funcs
Update OpCall to properly handle nil values passed to variadic
functions. Previously, passing nil as the last argument caused
an index out of range panic, and a single nil argument was
incorrectly treated as a nil slice. Added regression tests.

Signed-off-by: Ville Vesilehto <[email protected]>
  • Loading branch information
thevilledev committed Nov 30, 2025
commit 431bcfa592c0b4775740cbad9a415a3fb5c99ad3
33 changes: 33 additions & 0 deletions test/issues/817/issue_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package issue_test

import (
"fmt"
"testing"

"github.com/expr-lang/expr"
"github.com/expr-lang/expr/internal/testify/require"
)

func TestIssue817_1(t *testing.T) {
out, err := expr.Eval(
`sprintf("result: %v %v", 1, nil)`,
map[string]any{
"sprintf": fmt.Sprintf,
},
)
require.NoError(t, err)
require.Equal(t, "result: 1 <nil>", out)
}

func TestIssue817_2(t *testing.T) {
out, err := expr.Eval(
`thing(nil)`,
map[string]any{
"thing": func(arg ...any) string {
return fmt.Sprintf("result: (%T) %v", arg[0], arg[0])
},
},
)
require.NoError(t, err)
require.Equal(t, "result: (<nil>) <nil>", out)
}
20 changes: 18 additions & 2 deletions vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,13 +330,29 @@ func (vm *VM) Run(program *Program, env any) (_ any, err error) {
vm.push(runtime.Slice(node, from, to))

case OpCall:
fn := reflect.ValueOf(vm.pop())
v := vm.pop()
if v == nil {
panic("invalid operation: cannot call nil")
}
fn := reflect.ValueOf(v)
if fn.Kind() != reflect.Func {
panic(fmt.Sprintf("invalid operation: cannot call non-function of type %T", v))
}
fnType := fn.Type()
size := arg
in := make([]reflect.Value, size)
isVariadic := fnType.IsVariadic()
numIn := fnType.NumIn()
for i := int(size) - 1; i >= 0; i-- {
param := vm.pop()
if param == nil {
in[i] = reflect.Zero(fn.Type().In(i))
var inType reflect.Type
if isVariadic && i >= numIn-1 {
inType = fnType.In(numIn - 1).Elem()
} else {
inType = fnType.In(i)
}
in[i] = reflect.Zero(inType)
} else {
in[i] = reflect.ValueOf(param)
}
Expand Down
Loading