helpers.go provides easy functions to parse and evaluate expressions
This commit is contained in:
parent
d20027296c
commit
6d8c6f5154
57
helpers.go
Normal file
57
helpers.go
Normal file
@ -0,0 +1,57 @@
|
||||
// helpers.go
|
||||
package expr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func EvalString(ctx exprContext, source string) (result any, err error) {
|
||||
var tree *ast
|
||||
|
||||
r := strings.NewReader(source)
|
||||
scanner := NewScanner(r, DefaultTranslations())
|
||||
parser := NewParser(ctx)
|
||||
|
||||
if tree, err = parser.parse(scanner); err == nil {
|
||||
result, err = tree.eval(ctx)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type EvalArg struct {
|
||||
name string
|
||||
value any
|
||||
}
|
||||
|
||||
func EvalStringA(source string, args ...EvalArg) (result any, err error) {
|
||||
return EvalStringV(source, args)
|
||||
}
|
||||
|
||||
func EvalStringV(source string, args []EvalArg) (result any, err error) {
|
||||
ctx := NewSimpleFuncStore()
|
||||
for _, arg := range args {
|
||||
if isFunc(arg.value) {
|
||||
if f, ok := arg.value.(FuncTemplate); ok {
|
||||
ctx.addFunc(arg.name, f)
|
||||
} else {
|
||||
err = fmt.Errorf("invalid function specification: %q", arg.name)
|
||||
}
|
||||
} else if integer, ok := anyInteger(arg.value); ok {
|
||||
ctx.SetValue(arg.name, integer)
|
||||
} else if float, ok := anyFloat(arg.value); ok {
|
||||
ctx.SetValue(arg.name, float)
|
||||
} else if _, ok := arg.value.(string); ok {
|
||||
ctx.SetValue(arg.name, arg.value)
|
||||
} else if _, ok := arg.value.(bool); ok {
|
||||
ctx.SetValue(arg.name, arg.value)
|
||||
} else {
|
||||
err = fmt.Errorf("unsupported type %T specified for item %q", arg.value, arg.name)
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
result, err = EvalString(ctx, source)
|
||||
}
|
||||
return
|
||||
}
|
Loading…
Reference in New Issue
Block a user