From 56448f81ea4e9ab8edefa4973d0d45012532e20d Mon Sep 17 00:00:00 2001 From: Sergey Date: Sun, 17 Mar 2024 14:51:53 +0700 Subject: [PATCH] `expr.Operator` passes before `expr.Env` caused error (#606) --- checker/checker_test.go | 2 +- conf/config.go | 6 +++++- expr_test.go | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/checker/checker_test.go b/checker/checker_test.go index d6a84abc..29c50807 100644 --- a/checker/checker_test.go +++ b/checker/checker_test.go @@ -632,7 +632,7 @@ func TestCheck_TaggedFieldName(t *testing.T) { tree, err := parser.Parse(`foo.bar`) require.NoError(t, err) - config := &conf.Config{} + config := conf.CreateNew() expr.Env(struct { x struct { y bool `expr:"bar"` diff --git a/conf/config.go b/conf/config.go index 79989810..01a407a1 100644 --- a/conf/config.go +++ b/conf/config.go @@ -32,6 +32,7 @@ type Config struct { func CreateNew() *Config { c := &Config{ Optimize: true, + Types: make(TypesTable), ConstFns: make(map[string]reflect.Value), Functions: make(map[string]*builtin.Function), Builtins: make(map[string]*builtin.Function), @@ -62,7 +63,10 @@ func (c *Config) WithEnv(env any) { } c.Env = env - c.Types = CreateTypesTable(env) + types := CreateTypesTable(env) + for name, t := range types { + c.Types[name] = t + } c.MapEnv = mapEnv c.DefaultType = mapValueType c.Strict = true diff --git a/expr_test.go b/expr_test.go index 46cb8fe8..790fdd5d 100644 --- a/expr_test.go +++ b/expr_test.go @@ -2511,6 +2511,20 @@ func TestRaceCondition_variables(t *testing.T) { wg.Wait() } +func TestOperatorDependsOnEnv(t *testing.T) { + env := map[string]any{ + "plus": func(a, b int) int { + return 42 + }, + } + program, err := expr.Compile(`1 + 2`, expr.Operator("+", "plus"), expr.Env(env)) + require.NoError(t, err) + + out, err := expr.Run(program, env) + require.NoError(t, err) + assert.Equal(t, 42, out) +} + func TestArrayComparison(t *testing.T) { tests := []struct { env any