expr icon indicating copy to clipboard operation
expr copied to clipboard

Operating overloading does not work with functions defined using `expr.Function`

Open purplefox opened this issue 1 year ago • 2 comments

If you attempt to overload an operator and the implementation of the function is defined using expr.Function as opposed to having the function in the env, then it fails to compile.

Please see https://github.com/antonmedv/expr/discussions/360 for more details

purplefox avatar Apr 25 '23 08:04 purplefox

Here is the test that 🔴fails and needs to be fixed.

func TestOperator_Function(t *testing.T) {
	env := map[string]interface{}{
		"foo": Value{1},
		"bar": Value{2},
	}

	program, err := expr.Compile(
		`foo + bar`,
		expr.Env(env),
		expr.Operator("+", "Add"),
		expr.Function("Add", func(args ...interface{}) (interface{}, error) {
			return args[0].(Value).Int + args[1].(Value).Int, nil
		}),
	)
	require.NoError(t, err)

	output, err := expr.Run(program, env)
	require.NoError(t, err)
	require.Equal(t, 3, output)
}

type Value struct {
	Int int
}

Any volunteers? Tests should be added in https://github.com/antonmedv/expr/blob/master/test/operator/operator_test.go

antonmedv avatar Aug 14 '23 10:08 antonmedv

I tried to implement functionality that passes the test in https://github.com/antonmedv/expr/pull/408. It would be great if you can review the PR.

nikolaymatrosov avatar Aug 17 '23 11:08 nikolaymatrosov

Recently I was also troubled by this issue, I saw the issue, but I found that the new version does not seem to solve the problem

Q16G avatar Feb 14 '24 09:02 Q16G