Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support map as parameter #1

Merged
merged 3 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,13 @@ Fields are accessed in a similar way. Assuming `foo` has a field called "Length"

"foo.Length > 9000"

Accessors can be nested to any depth, like the following
The values of a `map` are accessed in the same way. Assuming the parameter `foo` is `map[string]int{ "bar": 1 }`

"foo.Bar.Baz.SomeFunction()"
"foo.bar == 1"

However it is not _currently_ supported to access values in `map`s. So the following will not work
Accessors can be nested to any depth, like the following

"foo.SomeMap['key']"
"foo.Bar.Baz.SomeFunction()"

This may be convenient, but note that using accessors involves a _lot_ of reflection. This makes the expression about four times slower than just using a parameter (consult the benchmarks for more precise measurements on your system).
If at all reasonable, the author recommends extracting the values you care about into a parameter map beforehand, or defining a struct that implements the `Parameters` interface, and which grabs fields as required. If there are functions you want to use, it's better to pass them as expression functions (see the above section). These approaches use no reflection, and are designed to be fast and clean.
Expand Down
11 changes: 9 additions & 2 deletions dummies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package govaluate
import (
"errors"
"fmt"
"strings"
)

/*
Expand All @@ -14,6 +15,7 @@ type dummyParameter struct {
BoolFalse bool
Nil interface{}
Nested dummyNestedParameter
Map map[string]interface{}
}

func (this dummyParameter) Func() string {
Expand All @@ -33,9 +35,9 @@ func (this dummyParameter) FuncArgStr(arg1 string) string {
}

func (this dummyParameter) TestArgs(str string, ui uint, ui8 uint8, ui16 uint16, ui32 uint32, ui64 uint64, i int, i8 int8, i16 int16, i32 int32, i64 int64, f32 float32, f64 float64, b bool) string {

var sum float64

sum = float64(ui) + float64(ui8) + float64(ui16) + float64(ui32) + float64(ui64)
sum += float64(i) + float64(i8) + float64(i16) + float64(i32) + float64(i64)
sum += float64(f32)
Expand Down Expand Up @@ -67,6 +69,11 @@ var dummyParameterInstance = dummyParameter{
Nested: dummyNestedParameter{
Funk: "funkalicious",
},
Map: map[string]interface{}{
"String": "string!",
"Int": 101,
"StringCompare": strings.Compare,
},
}

var fooParameter = EvaluationParameter{
Expand Down
13 changes: 13 additions & 0 deletions evaluationFailure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (
TOO_FEW_ARGS = "Too few arguments to parameter call"
TOO_MANY_ARGS = "Too many arguments to parameter call"
MISMATCHED_PARAMETERS = "Argument type conversion failed"
UNEXPORTED_ACCESSOR = "Unable to access unexported"
)

// preset parameter map of types that can be used in an evaluation failure test to check typing.
Expand Down Expand Up @@ -488,6 +489,18 @@ func TestInvalidParameterCalls(test *testing.T) {
Parameters: fooFailureParameters,
Expected: MISMATCHED_PARAMETERS,
},
EvaluationFailureTest{
Name: "Unexported parameter access",
Input: "foo.bar",
Parameters: map[string]interface{}{
"foo": struct {
bar string
}{
bar: "baz",
},
},
Expected: UNEXPORTED_ACCESSOR,
},
}

runEvaluationFailureTests(evaluationTests, test)
Expand Down
51 changes: 38 additions & 13 deletions evaluationStage.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"reflect"
"regexp"
"strings"
"unicode"
)

const (
Expand Down Expand Up @@ -313,6 +314,7 @@ func makeAccessorStage(pair []string) evaluationOperator {
}
}()

LOOP:
for i := 1; i < len(pair); i++ {

coreValue := reflect.ValueOf(value)
Expand All @@ -325,24 +327,47 @@ func makeAccessorStage(pair []string) evaluationOperator {
coreValue = coreValue.Elem()
}

if coreValue.Kind() != reflect.Struct {
return nil, errors.New("Unable to access '" + pair[i] + "', '" + pair[i-1] + "' is not a struct")
}
var field reflect.Value
var method reflect.Value

field := coreValue.FieldByName(pair[i])
if field != (reflect.Value{}) {
value = field.Interface()
continue
}
switch coreValue.Kind() {
case reflect.Struct:
// check if field is exported
firstCharacter := getFirstRune(pair[i])
if unicode.ToUpper(firstCharacter) != firstCharacter {
errorMsg := fmt.Sprintf("Unable to access unexported field '%s' in '%s'", pair[i], pair[i-1])
return nil, errors.New(errorMsg)
}

method := coreValue.MethodByName(pair[i])
if method == (reflect.Value{}) {
if corePtrVal.IsValid() {
method = corePtrVal.MethodByName(pair[i])
field = coreValue.FieldByName(pair[i])
if field != (reflect.Value{}) {
value = field.Interface()
continue LOOP
}

method = coreValue.MethodByName(pair[i])
if method == (reflect.Value{}) {
return nil, errors.New("No method or field '" + pair[i] + "' present on parameter '" + pair[i-1] + "'")
if corePtrVal.IsValid() {
method = corePtrVal.MethodByName(pair[i])
}
}
case reflect.Map:
field = coreValue.MapIndex(reflect.ValueOf(pair[i]))
if field != (reflect.Value{}) {
inter := field.Interface()
if reflect.TypeOf(inter).Kind() == reflect.Func {
method = reflect.ValueOf(inter)
} else {
value = inter
continue LOOP
}
}
default:
return nil, errors.New("Unable to access '" + pair[i] + "', '" + pair[i-1] + "' is not a struct or map")
}

if method == (reflect.Value{}) {
return nil, errors.New("No method or field '" + pair[i] + "' present on parameter '" + pair[i-1] + "'")
}

switch right := right.(type) {
Expand Down
16 changes: 15 additions & 1 deletion evaluation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ func TestNoParameterEvaluation(test *testing.T) {
Expected: true,
},
EvaluationTest{

Name: "Ternary/Java EL ambiguity",
Input: "false ? foo:length()",
Functions: map[string]ExpressionFunction{
Expand Down Expand Up @@ -1391,6 +1391,20 @@ func TestParameterizedEvaluation(test *testing.T) {
Parameters: []EvaluationParameter{fooParameter},
Expected: "funkalicious",
},
EvaluationTest{

Name: "Nested Map string",
Input: "foo.Map.String",
Parameters: []EvaluationParameter{fooParameter},
Expected: "string!",
},
EvaluationTest{

Name: "Nested Map function",
Input: `foo.Map.StringCompare("foo", "bar")`,
Parameters: []EvaluationParameter{fooParameter},
Expected: 1.0,
},
EvaluationTest{

Name: "Parameter call with + modifier",
Expand Down
11 changes: 0 additions & 11 deletions parsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,17 +186,6 @@ func readToken(stream *lexerStream, state lexerState, functions map[string]Expre
kind = ACCESSOR
splits := strings.Split(tokenString, ".")
tokenValue = splits

// check that none of them are unexported
for i := 1; i < len(splits); i++ {

firstCharacter := getFirstRune(splits[i])

if unicode.ToUpper(firstCharacter) != firstCharacter {
errorMsg := fmt.Sprintf("Unable to access unexported field '%s' in token '%s'", splits[i], tokenString)
return ExpressionToken{}, errors.New(errorMsg), false
}
}
}
break
}
Expand Down
8 changes: 0 additions & 8 deletions parsingFailure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const (
INVALID_NUMERIC = "Unable to parse numeric value"
UNDEFINED_FUNCTION = "Undefined function"
HANGING_ACCESSOR = "Hanging accessor on token"
UNEXPORTED_ACCESSOR = "Unable to access unexported"
INVALID_HEX = "Unable to parse hex value"
)

Expand Down Expand Up @@ -178,13 +177,6 @@ func TestParsingFailure(test *testing.T) {
Input: "foo.Bar.",
Expected: HANGING_ACCESSOR,
},
ParsingFailureTest{

// this is expected to change once there are structtags in place that allow aliasing of fields
Name: "Unexported parameter access",
Input: "foo.bar",
Expected: UNEXPORTED_ACCESSOR,
},
ParsingFailureTest{
Name: "Incomplete Hex",
Input: "0x",
Expand Down
Loading