Skip to content

Commit

Permalink
pkg/nsrule: Allow operators to be overloaded
Browse files Browse the repository at this point in the history
  • Loading branch information
pg9182 committed Sep 14, 2023
1 parent 9a47702 commit e51d20e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
41 changes: 39 additions & 2 deletions pkg/nsrule/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ package nsrule

import (
"maps"
"reflect"

"github.com/antonmedv/expr"
)

// Env contains data used to evaluate rules.
type Env map[string]any

var (
dummyEnv = Env{}
defaultEnv = Env{}
dummyEnv = Env{}
defaultEnv = Env{}
extraOptions []expr.Option
)

// NewEnv shallow-copies the default values into a new Env.
Expand Down Expand Up @@ -43,3 +47,36 @@ func Define[T any](name string) func(Env, T) {
func DefineDefault[T any](name string, def T) func(Env, T) {
return define[T](name, def, false)
}

// DefineOperator overloads an operator.
func DefineOperator[T any](op string, fn T) string {
name := op + " " + reflect.TypeOf(fn).String()
extraOptions = append(extraOptions, expr.Operator(op, name))
define[T](name, fn, false)
return name
}

// DefineOperatorCompare is shorthand for using DefineOperator to override
// comparison operators.
func DefineOperatorCompare[A, B any](cmp func(a A, b B) int) []string {
var ops []string
ops = append(ops, DefineOperator("<", func(a A, b B) bool {
return cmp(a, b) < 0
}))
ops = append(ops, DefineOperator("<=", func(a A, b B) bool {
return cmp(a, b) <= 0
}))
ops = append(ops, DefineOperator("==", func(a A, b B) bool {
return cmp(a, b) == 0
}))
ops = append(ops, DefineOperator("!=", func(a A, b B) bool {
return cmp(a, b) != 0
}))
ops = append(ops, DefineOperator(">=", func(a A, b B) bool {
return cmp(a, b) >= 0
}))
ops = append(ops, DefineOperator(">", func(a A, b B) bool {
return cmp(a, b) > 0
}))
return ops
}
2 changes: 1 addition & 1 deletion pkg/nsrule/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func ParseRules(r io.Reader, name string) ([]Rule, error) {
name: name,
line: expN,
}
if v, err := expr.Compile(expB.String(), expr.AsBool(), expr.Optimize(true), expr.Env(dummyEnv)); err != nil { // TODO: dummy env
if v, err := expr.Compile(expB.String(), append([]expr.Option{expr.AsBool(), expr.Optimize(true), expr.Env(dummyEnv)}, extraOptions...)...); err != nil { // TODO: dummy env
return rs, fmt.Errorf("line %d: compile rule expression: %w", expN, err)
} else {
r.expr = v
Expand Down

0 comments on commit e51d20e

Please sign in to comment.