-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtest_compiler_test.go
More file actions
346 lines (321 loc) · 8.19 KB
/
Copy pathtest_compiler_test.go
File metadata and controls
346 lines (321 loc) · 8.19 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package workflow
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/deepnoodle-ai/workflow/script"
)
// testCompiler is a tiny expression evaluator used by workflow tests that
// need the path layer to compile and evaluate expressions without pulling in
// a real scripting engine. It supports the small subset of syntax required
// by the tests:
//
// - dotted identifier paths: foo.bar.baz
// - integer literals: 42
// - string literals: "text" or 'text'
// - array literals of simple elements: [1, 2, 3]
// - binary operators: + - * / > < >= <= == !=
//
// It deliberately does not handle parentheses, function calls, or nested
// expressions. Anything outside this grammar returns a compile error.
type testCompiler struct{}
// NewTestCompiler returns the package's test stub compiler. It is exported
// only through this test file so that external test packages
// (package workflow_test) can reach it the same way the internal test
// package does.
func NewTestCompiler() script.Compiler { return testCompiler{} }
func newTestCompiler() script.Compiler { return testCompiler{} }
func (testCompiler) Compile(ctx context.Context, code string) (script.Script, error) {
code = strings.TrimSpace(code)
if code == "" {
return nil, fmt.Errorf("empty expression")
}
node, err := parseTestExpr(code)
if err != nil {
return nil, fmt.Errorf("invalid expression %q: %w", code, err)
}
return &testScript{node: node}, nil
}
type testScript struct {
node testNode
}
func (s *testScript) Evaluate(ctx context.Context, globals map[string]any) (script.Value, error) {
v, err := s.node.eval(globals)
if err != nil {
return nil, err
}
return &testValue{v: v}, nil
}
type testValue struct{ v any }
func (t *testValue) Value() any { return t.v }
func (t *testValue) Items() ([]any, error) { return script.EachValue(t.v) }
func (t *testValue) String() string { return fmt.Sprintf("%v", t.v) }
func (t *testValue) IsTruthy() bool { return script.IsTruthyValue(t.v) }
type testNode interface {
eval(globals map[string]any) (any, error)
}
type literalNode struct{ v any }
func (l literalNode) eval(map[string]any) (any, error) { return l.v, nil }
type arrayNode struct{ items []testNode }
func (a arrayNode) eval(globals map[string]any) (any, error) {
result := make([]any, len(a.items))
for i, item := range a.items {
v, err := item.eval(globals)
if err != nil {
return nil, err
}
result[i] = v
}
return result, nil
}
type pathNode struct{ segments []string }
func (p pathNode) eval(globals map[string]any) (any, error) {
var current any = globals
for i, seg := range p.segments {
m, ok := current.(map[string]any)
if !ok {
return nil, fmt.Errorf("undefined variable %q: not a map at segment %d", strings.Join(p.segments, "."), i)
}
v, ok := m[seg]
if !ok {
return nil, fmt.Errorf("undefined variable %q", strings.Join(p.segments, "."))
}
current = v
}
return current, nil
}
type binaryNode struct {
op string
lhs, rhs testNode
}
func (b binaryNode) eval(globals map[string]any) (any, error) {
lv, err := b.lhs.eval(globals)
if err != nil {
return nil, err
}
if b.op == "&&" || b.op == "||" {
lb := script.IsTruthyValue(lv)
if b.op == "&&" && !lb {
return false, nil
}
if b.op == "||" && lb {
return true, nil
}
rv, err := b.rhs.eval(globals)
if err != nil {
return nil, err
}
return script.IsTruthyValue(rv), nil
}
rv, err := b.rhs.eval(globals)
if err != nil {
return nil, err
}
// Equality works across types (string-string, numeric-numeric, bool-bool).
if b.op == "==" || b.op == "!=" {
if lf, lok := toFloat(lv); lok {
if rf, rok := toFloat(rv); rok {
eq := lf == rf
if b.op == "!=" {
eq = !eq
}
return eq, nil
}
}
eq := lv == rv
if b.op == "!=" {
eq = !eq
}
return eq, nil
}
lf, lok := toFloat(lv)
rf, rok := toFloat(rv)
if !lok || !rok {
return nil, fmt.Errorf("non-numeric operand in %v %s %v", lv, b.op, rv)
}
switch b.op {
case "+":
return lf + rf, nil
case "-":
return lf - rf, nil
case "*":
return lf * rf, nil
case "/":
if rf == 0 {
return nil, fmt.Errorf("division by zero")
}
return lf / rf, nil
case ">":
return lf > rf, nil
case "<":
return lf < rf, nil
case ">=":
return lf >= rf, nil
case "<=":
return lf <= rf, nil
}
return nil, fmt.Errorf("unsupported operator %q", b.op)
}
func toFloat(v any) (float64, bool) {
switch n := v.(type) {
case int:
return float64(n), true
case int32:
return float64(n), true
case int64:
return float64(n), true
case float32:
return float64(n), true
case float64:
return n, true
}
return 0, false
}
// parseTestExpr parses the limited grammar supported by testCompiler.
// Precedence (lowest to highest): ||, &&, comparison, additive, multiplicative.
func parseTestExpr(s string) (testNode, error) {
s = strings.TrimSpace(s)
// Logical operators first (lowest precedence).
for _, op := range []string{"||", "&&"} {
if idx := findOp(s, op); idx >= 0 {
return parseBinary(s, idx, len(op), op)
}
}
// Comparison operators.
for _, op := range []string{">=", "<=", "==", "!="} {
if idx := findOp(s, op); idx >= 0 {
return parseBinary(s, idx, len(op), op)
}
}
for _, op := range []string{">", "<"} {
if idx := findOp(s, op); idx >= 0 {
return parseBinary(s, idx, len(op), op)
}
}
// Arithmetic operators.
for _, op := range []string{"+", "-", "*", "/"} {
if idx := findOp(s, op); idx >= 0 {
return parseBinary(s, idx, len(op), op)
}
}
return parseAtom(s)
}
func parseBinary(s string, idx, oplen int, op string) (testNode, error) {
lhs, err := parseTestExpr(strings.TrimSpace(s[:idx]))
if err != nil {
return nil, err
}
rhs, err := parseTestExpr(strings.TrimSpace(s[idx+oplen:]))
if err != nil {
return nil, err
}
return binaryNode{op: op, lhs: lhs, rhs: rhs}, nil
}
// findOp finds an operator in s, ignoring operators inside [ ] and quotes,
// and skipping characters that are part of other operators (e.g. "<" inside "<=").
func findOp(s string, op string) int {
depth := 0
inQuote := byte(0)
for i := 0; i < len(s); i++ {
c := s[i]
if inQuote != 0 {
if c == inQuote {
inQuote = 0
}
continue
}
switch c {
case '"', '\'':
inQuote = c
continue
case '[':
depth++
continue
case ']':
depth--
continue
}
if depth > 0 {
continue
}
if i+len(op) > len(s) {
continue
}
if s[i:i+len(op)] != op {
continue
}
// Avoid matching the "<" in "<=" or ">" in ">=" when caller asked for the single-char form.
if len(op) == 1 && (op == "<" || op == ">" || op == "=" || op == "!") {
if i+1 < len(s) && s[i+1] == '=' {
continue
}
}
return i
}
return -1
}
func parseAtom(s string) (testNode, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, fmt.Errorf("empty atom")
}
// Array literal
if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
inner := strings.TrimSpace(s[1 : len(s)-1])
if inner == "" {
return arrayNode{}, nil
}
parts := strings.Split(inner, ",")
items := make([]testNode, 0, len(parts))
for _, part := range parts {
node, err := parseAtom(strings.TrimSpace(part))
if err != nil {
return nil, err
}
items = append(items, node)
}
return arrayNode{items: items}, nil
}
// String literal
if (strings.HasPrefix(s, `"`) && strings.HasSuffix(s, `"`)) ||
(strings.HasPrefix(s, `'`) && strings.HasSuffix(s, `'`)) {
return literalNode{v: s[1 : len(s)-1]}, nil
}
// Int literal
if n, err := strconv.Atoi(s); err == nil {
return literalNode{v: n}, nil
}
// Float literal
if f, err := strconv.ParseFloat(s, 64); err == nil {
return literalNode{v: f}, nil
}
// Bool literal
if s == "true" {
return literalNode{v: true}, nil
}
if s == "false" {
return literalNode{v: false}, nil
}
// Dotted identifier path
if isIdentifierPath(s) {
return pathNode{segments: strings.Split(s, ".")}, nil
}
return nil, fmt.Errorf("unrecognized atom %q", s)
}
func isIdentifierPath(s string) bool {
if s == "" {
return false
}
for _, part := range strings.Split(s, ".") {
if part == "" {
return false
}
for i, r := range part {
if !(r == '_' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (i > 0 && r >= '0' && r <= '9')) {
return false
}
}
}
return true
}