[Feature] Allow to use function defined in a Fetcher
Today the fetcher.Fetch is ignored for function calls, making it impossible to create functions at runtime.
This PR adds this feature, allowing the build below to take place.
type FetcherMap struct {
data map[string]interface{}
}
func (m *FetcherMap) Set(key string, value interface{}) {
if m.data == nil {
m.data = map[string]interface{}{}
}
m.data[key] = value
}
func (m *FetcherMap) Fetch(key interface{}) interface{} {
if keyStr, ok := key.(string); ok {
if value, exists := m.data[keyStr]; exists {
return value
}
}
return nil
}
func TestRun_fetch_functions(t *testing.T) {
input := `hello() + world() + suffix()`
tree, err := parser.Parse(input)
require.NoError(t, err)
program, err := compiler.Compile(tree, nil)
require.NoError(t, err)
fetcher := &FetcherMap{}
fetcher.Set("hello", func() string { return "hello " })
fetcher.Set("world", func() string { return "world" })
suffixFnPtr := func() string { return "!" }
fetcher.Set("suffix", &suffixFnPtr)
out, err := vm.Run(program, fetcher)
require.NoError(t, err)
require.Equal(t, "hello world!", out)
}
fix https://github.com/antonmedv/expr/issues/247

fix https://github.com/antonmedv/expr/issues/217
Can we update exprgen as well?
I couldn't identify the relationship of exprgen with FetchFn.
I'm actually working on refactoring right now.
As vm.Fetcher is removed completely (see #274) this PR is obsolete.
One workaround is to use ast.Patch.