forked from deepnoodle-ai/workflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_compiler.go
More file actions
58 lines (49 loc) · 1.61 KB
/
script_compiler.go
File metadata and controls
58 lines (49 loc) · 1.61 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package workflow
import (
"context"
"fmt"
"github.com/deepnoodle-ai/expr"
"github.com/deepnoodle-ai/workflow/script"
)
// DefaultScriptCompiler returns a script.Compiler backed by
// github.com/deepnoodle-ai/expr with the standard builtin function set
// enabled. This is the compiler used by NewExecution when
// ExecutionOptions.ScriptCompiler is nil — it handles edge conditions
// and ${...} parameter templates out of the box.
//
// expr is expression-only: it cannot mutate state, so workflows that
// need state-mutating scripts must provide their own script.Compiler
// (for example, by wrapping a language like Risor behind the
// script.Compiler interface).
func DefaultScriptCompiler() script.Compiler {
return exprCompiler{}
}
type exprCompiler struct{}
func (exprCompiler) Compile(ctx context.Context, code string) (script.Script, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
p, err := expr.Compile(code, expr.WithBuiltins())
if err != nil {
return nil, err
}
return exprScript{program: p}, nil
}
type exprScript struct{ program *expr.Program }
func (s exprScript) Evaluate(ctx context.Context, globals map[string]any) (script.Value, error) {
v, err := s.program.Run(ctx, globals)
if err != nil {
return nil, err
}
return exprValue{v: v}, nil
}
type exprValue struct{ v any }
func (v exprValue) Value() any { return v.v }
func (v exprValue) IsTruthy() bool { return script.IsTruthyValue(v.v) }
func (v exprValue) Items() ([]any, error) { return script.EachValue(v.v) }
func (v exprValue) String() string {
if v.v == nil {
return ""
}
return fmt.Sprintf("%v", v.v)
}