expr/simple-func-store.go

86 lines
1.7 KiB
Go
Raw Normal View History

2024-03-28 06:29:11 +01:00
// simple-var-store.go
package expr
import "fmt"
type SimpleFuncStore struct {
varStore map[string]any
funcStore map[string]Functor
2024-03-28 06:29:11 +01:00
}
type funcInfo struct {
name string
// minArgs int
// maxArgs int
}
func (info *funcInfo) Name() string {
return info.name
}
func (info *funcInfo) MinArgs() int {
return 0
}
func (info *funcInfo) MaxArgs() int {
return -1
}
func NewSimpleFuncStore() *SimpleFuncStore {
return &SimpleFuncStore{
varStore: make(map[string]any),
funcStore: make(map[string]Functor),
}
}
func (ctx *SimpleFuncStore) Clone() exprContext {
return &SimpleFuncStore{
varStore: CloneMap(ctx.varStore),
funcStore: CloneMap(ctx.funcStore),
2024-03-28 06:29:11 +01:00
}
}
func (ctx *SimpleFuncStore) GetVar(varName string) (v any, exists bool) {
2024-03-28 06:29:11 +01:00
v, exists = ctx.varStore[varName]
return
}
func (ctx *SimpleFuncStore) SetVar(varName string, value any) {
2024-03-28 06:29:11 +01:00
ctx.varStore[varName] = value
}
func (ctx *SimpleFuncStore) EnumVars(acceptor func(name string) (accept bool)) (varNames []string) {
varNames = make([]string, 0)
for name := range ctx.varStore {
if acceptor != nil {
if acceptor(name) {
varNames = append(varNames, name)
}
} else {
varNames = append(varNames, name)
}
}
return
}
2024-03-28 06:29:11 +01:00
func (ctx *SimpleFuncStore) GetFuncInfo(name string) (f exprFunc) {
var exists bool
if _, exists = ctx.funcStore[name]; exists {
f = &funcInfo{name: name}
}
return
}
func (ctx *SimpleFuncStore) RegisterFunc(name string, functor Functor, minArgs, maxArgs int) {
ctx.funcStore[name] = functor
2024-03-28 06:29:11 +01:00
}
func (ctx *SimpleFuncStore) Call(name string, args []any) (result any, err error) {
if functor, exists := ctx.funcStore[name]; exists {
result, err = functor.Invoke(ctx, name, args)
2024-03-28 06:29:11 +01:00
} else {
err = fmt.Errorf("unknown function %s()", name)
}
return
}