summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/d5/tengo/v2/eval.go
blob: 9ce9b2a7332365f1761282e3a21246ddec0122ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package tengo

import (
	"context"
	"fmt"
	"strings"
)

// Eval compiles and executes given expr with params, and returns an
// evaluated value. expr must be an expression. Otherwise it will fail to
// compile. Expression must not use or define variable "__res__" as it's
// reserved for the internal usage.
func Eval(
	ctx context.Context,
	expr string,
	params map[string]interface{},
) (interface{}, error) {
	expr = strings.TrimSpace(expr)
	if expr == "" {
		return nil, fmt.Errorf("empty expression")
	}

	script := NewScript([]byte(fmt.Sprintf("__res__ := (%s)", expr)))
	for pk, pv := range params {
		err := script.Add(pk, pv)
		if err != nil {
			return nil, fmt.Errorf("script add: %w", err)
		}
	}
	compiled, err := script.RunContext(ctx)
	if err != nil {
		return nil, fmt.Errorf("script run: %w", err)
	}
	return compiled.Get("__res__").Value(), nil
}