expr icon indicating copy to clipboard operation
expr copied to clipboard

[Feature] Allow to use function defined in a Fetcher

Open nidorx opened this issue 3 years ago • 1 comments

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

image

nidorx avatar Sep 03 '22 01:09 nidorx

fix https://github.com/antonmedv/expr/issues/217

nidorx avatar Sep 03 '22 01:09 nidorx

Can we update exprgen as well?

antonmedv avatar Oct 06 '22 20:10 antonmedv

I couldn't identify the relationship of exprgen with FetchFn.

nidorx avatar Oct 12 '22 17:10 nidorx

I'm actually working on refactoring right now.

antonmedv avatar Oct 13 '22 12:10 antonmedv

As vm.Fetcher is removed completely (see #274) this PR is obsolete.

One workaround is to use ast.Patch.

antonmedv avatar Nov 05 '22 18:11 antonmedv