-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
pkg/nsrule: Allow packages to extend env
- Loading branch information
Showing
2 changed files
with
38 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,45 @@ | ||
package nsrule | ||
|
||
import "github.com/antonmedv/expr" | ||
import ( | ||
"maps" | ||
) | ||
|
||
// Env contains data used to evaluate rules. | ||
type Env struct { | ||
env map[string]any | ||
} | ||
type Env map[string]any | ||
|
||
var dummyEnv = expr.Env(NewEnv().env) | ||
var ( | ||
dummyEnv = Env{} | ||
defaultEnv = Env{} | ||
) | ||
|
||
// NewEnv initializes an env using the provided information. | ||
// | ||
// TODO | ||
// NewEnv shallow-copies the default values into a new Env. | ||
func NewEnv() Env { | ||
env := map[string]any{} | ||
return Env{env} | ||
return maps.Clone(defaultEnv) | ||
} | ||
|
||
func define[T any](name string, def T, optional bool) func(Env, T) { | ||
if name == "" { | ||
panic("define: name is required") | ||
} | ||
if _, ok := dummyEnv[name]; ok { | ||
panic("define: name is already used") | ||
} | ||
dummyEnv[name] = def | ||
if !optional { | ||
defaultEnv[name] = def | ||
} | ||
return func(e Env, v T) { e[name] = v } | ||
} | ||
|
||
// Define registers an optional variable with the provided name. For parse-time | ||
// expression type-checking to work, T should not be any. | ||
func Define[T any](name string) func(Env, T) { | ||
var zero T | ||
return define[T](name, zero, true) | ||
} | ||
|
||
// DefineDefault registers a variable with the provided name. For parse-time | ||
// expression type-checking to work, T should not be any. | ||
func DefineDefault[T any](name string, def T) func(Env, T) { | ||
return define[T](name, def, false) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters