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 4e929b8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
16 changes: 14 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,11 @@ 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
}
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 4e929b8

Please sign in to comment.