-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcondition.go
More file actions
478 lines (421 loc) · 9.77 KB
/
Copy pathcondition.go
File metadata and controls
478 lines (421 loc) · 9.77 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Package validation — condition mini-language
//
// The condition language is a small expression evaluator used by conditional
// validation rules (RequiredIf, RequiredUnless, When, Unless) to express
// cross-field dependencies. It is intentionally minimal: no assignment, no
// loops, no user-defined functions.
//
// # Grammar
//
// expr = or
// or = and { "||" and }
// and = cmp { "&&" cmp }
// cmp = unary [ op unary ]
// unary = "!" atom | atom
// atom = "(" expr ")" | call | ident | string | int | float | bool
// call = name "(" ident ")"
// op = "==" | "!=" | "<" | ">" | "<=" | ">="
//
// # Literals
//
// - String: "hello" or 'hello' (either quote style, no escape sequences)
// - Integer: 42
// - Float: 3.14
// - Boolean: true | false
//
// # Identifiers
//
// Unquoted identifiers are resolved as dot-separated field paths against the
// current InputBag (e.g. "user.role" looks up input["user"]["role"]). An
// identifier that does not exist in the input resolves to nil.
//
// # Functions
//
// - exists(path): true if the field at path is present in the input.
// - len(path): length of the value at path (string, slice, or map).
// Returns 0 when the field is absent or its type has no length.
//
// # Examples
//
// role == "admin"
// age >= 18 && verified == true
// (status == "active" || status == "pending") && exists(email)
// len(tags) > 0 && len(tags) <= 5
// exists(order.items) && len(order.items) > 0
package validation
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"unicode"
)
type cTokKind int
const (
cTokEOF cTokKind = iota
cTokAND
cTokOR
cTokNOT
cTokLParen
cTokRParen
cTokEQ
cTokNEQ
cTokLT
cTokGT
cTokLTE
cTokGTE
cTokIdent
cTokString
cTokInt
cTokFloat
cTokBool
)
type cTok struct {
kind cTokKind
val string
}
//nolint:gocyclo // this function is complex by nature.
func condTokenize(s string) ([]cTok, error) {
var tokens []cTok
i := 0
for i < len(s) {
if unicode.IsSpace(rune(s[i])) {
i++
continue
}
switch {
case strings.HasPrefix(s[i:], "&&"):
tokens = append(tokens, cTok{cTokAND, "&&"})
i += 2
case strings.HasPrefix(s[i:], "||"):
tokens = append(tokens, cTok{cTokOR, "||"})
i += 2
case strings.HasPrefix(s[i:], "=="):
tokens = append(tokens, cTok{cTokEQ, "=="})
i += 2
case strings.HasPrefix(s[i:], "!="):
tokens = append(tokens, cTok{cTokNEQ, "!="})
i += 2
case strings.HasPrefix(s[i:], "<="):
tokens = append(tokens, cTok{cTokLTE, "<="})
i += 2
case strings.HasPrefix(s[i:], ">="):
tokens = append(tokens, cTok{cTokGTE, ">="})
i += 2
case s[i] == '<':
tokens = append(tokens, cTok{cTokLT, "<"})
i++
case s[i] == '>':
tokens = append(tokens, cTok{cTokGT, ">"})
i++
case s[i] == '!':
tokens = append(tokens, cTok{cTokNOT, "!"})
i++
case s[i] == '(':
tokens = append(tokens, cTok{cTokLParen, "("})
i++
case s[i] == ')':
tokens = append(tokens, cTok{cTokRParen, ")"})
i++
case s[i] == '"' || s[i] == '\'':
quote := s[i]
i++
start := i
for i < len(s) && s[i] != quote {
i++
}
tokens = append(tokens, cTok{cTokString, s[start:i]})
if i < len(s) {
i++
}
case unicode.IsDigit(rune(s[i])):
start := i
isFloat := false
for i < len(s) && (unicode.IsDigit(rune(s[i])) || s[i] == '.') {
if s[i] == '.' {
if isFloat {
return nil, fmt.Errorf("invalid numeric literal %q", s[start:i+1])
}
isFloat = true
}
i++
}
if isFloat {
tokens = append(tokens, cTok{cTokFloat, s[start:i]})
} else {
tokens = append(tokens, cTok{cTokInt, s[start:i]})
}
case unicode.IsLetter(rune(s[i])) || s[i] == '_':
start := i
for i < len(s) && (unicode.IsLetter(rune(s[i])) || unicode.IsDigit(rune(s[i])) || s[i] == '_' || s[i] == '.') {
i++
}
word := s[start:i]
switch word {
case "true", "false":
tokens = append(tokens, cTok{cTokBool, word})
default:
tokens = append(tokens, cTok{cTokIdent, word})
}
default:
i++
}
}
tokens = append(tokens, cTok{cTokEOF, ""})
return tokens, nil
}
type condParser struct {
tokens []cTok
pos int
input *InputBag
}
func (p *condParser) peek() cTok {
if p.pos < len(p.tokens) {
return p.tokens[p.pos]
}
return cTok{cTokEOF, ""}
}
func (p *condParser) consume() cTok {
t := p.peek()
p.pos++
return t
}
func (p *condParser) parseOr() (bool, error) {
left, err := p.parseAnd()
if err != nil {
return false, err
}
for p.peek().kind == cTokOR {
p.consume()
right, err := p.parseAnd()
if err != nil {
return false, err
}
left = left || right
}
return left, nil
}
func (p *condParser) parseAnd() (bool, error) {
left, err := p.parseCmp()
if err != nil {
return false, err
}
for p.peek().kind == cTokAND {
p.consume()
right, err := p.parseCmp()
if err != nil {
return false, err
}
left = left && right
}
return left, nil
}
func (p *condParser) parseCmp() (bool, error) {
left, err := p.parseUnary()
if err != nil {
return false, err
}
opTok := p.peek()
switch opTok.kind {
case cTokEQ, cTokNEQ, cTokLT, cTokGT, cTokLTE, cTokGTE:
p.consume()
right, err := p.parseUnary()
if err != nil {
return false, err
}
return condCompare(left, opTok.kind, right)
}
if b, ok := left.(bool); ok {
return b, nil
}
return false, fmt.Errorf("value %v is not boolean and has no comparison operator", left)
}
func (p *condParser) parseUnary() (any, error) {
if p.peek().kind == cTokNOT {
p.consume()
val, err := p.parseAtom()
if err != nil {
return nil, err
}
b, ok := val.(bool)
if !ok {
return nil, fmt.Errorf("! requires a boolean operand, got %T", val)
}
return !b, nil
}
return p.parseAtom()
}
func (p *condParser) parseAtom() (any, error) {
t := p.peek()
switch t.kind {
case cTokLParen:
p.consume()
b, err := p.parseOr()
if err != nil {
return nil, err
}
if p.peek().kind != cTokRParen {
return nil, errors.New("expected closing )")
}
p.consume()
return b, nil
case cTokIdent:
if p.pos+1 < len(p.tokens) && p.tokens[p.pos+1].kind == cTokLParen {
return p.parseCall()
}
p.consume()
val, _ := p.input.Lookup(t.val)
return val, nil
case cTokString:
p.consume()
return t.val, nil
case cTokInt:
p.consume()
n, _ := strconv.Atoi(t.val) //nolint:errcheck // no need to check we already know t.val is an int
return n, nil
case cTokFloat:
p.consume()
f, _ := strconv.ParseFloat(t.val, 64) //nolint:errcheck // no need to check we already know t.val is a float
return f, nil
case cTokBool:
p.consume()
return t.val == "true", nil
}
return nil, fmt.Errorf("unexpected token %q", t.val)
}
func (p *condParser) parseCall() (any, error) {
name := p.consume().val
p.consume() // consume "("
if p.peek().kind != cTokIdent {
return nil, fmt.Errorf("%s() expects a field path argument", name)
}
arg := p.consume().val
if p.peek().kind != cTokRParen {
return nil, fmt.Errorf("expected ) after argument in %s()", name)
}
p.consume()
switch name {
case "exists":
_, ok := p.input.Lookup(arg)
return ok, nil
case "len":
val, ok := p.input.Lookup(arg)
if !ok {
return 0, nil
}
return condLen(val), nil
default:
return nil, fmt.Errorf("unknown function %q", name)
}
}
// condLen returns the length of val for use in len() conditions.
// Handles string, []any, and any reflect-accessible slice/array/map/string.
// Returns 0 for nil and non-collection types.
func condLen(val any) int {
if val == nil {
return 0
}
switch v := val.(type) {
case string:
return len(v)
case []any:
return len(v)
}
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.Slice, reflect.Array, reflect.Map, reflect.String:
return rv.Len()
}
return 0
}
// condCompare evaluates left op right.
// Numeric types are both promoted to float64 before comparison.
// All other type pairs are compared as strings via fmt.Sprintf("%v").
func condCompare(left any, op cTokKind, right any) (bool, error) {
lf, lNum := condToFloat(left)
rf, rNum := condToFloat(right)
if lNum && rNum {
switch op {
case cTokEQ:
return lf == rf, nil
case cTokNEQ:
return lf != rf, nil
case cTokLT:
return lf < rf, nil
case cTokGT:
return lf > rf, nil
case cTokLTE:
return lf <= rf, nil
case cTokGTE:
return lf >= rf, nil
}
}
ls := fmt.Sprintf("%v", left)
rs := fmt.Sprintf("%v", right)
switch op {
case cTokEQ:
return ls == rs, nil
case cTokNEQ:
return ls != rs, nil
case cTokLT:
return ls < rs, nil
case cTokGT:
return ls > rs, nil
case cTokLTE:
return ls <= rs, nil
case cTokGTE:
return ls >= rs, nil
default:
return false, errors.New("unsupported comparison operator")
}
}
// condToFloat converts any Go numeric type to float64.
// Returns (0, false) for non-numeric types.
func condToFloat(v any) (float64, bool) {
switch n := v.(type) {
case int:
return float64(n), true
case int8:
return float64(n), true
case int16:
return float64(n), true
case int32:
return float64(n), true
case int64:
return float64(n), true
case uint:
return float64(n), true
case uint8:
return float64(n), true
case uint16:
return float64(n), true
case uint32:
return float64(n), true
case uint64:
return float64(n), true
case float32:
return float64(n), true
case float64:
return n, true
default:
return 0, false
}
}
// evalCondition parses and evaluates a condition expression against input.
// Returns an error for syntax errors, unknown functions, or type mismatches.
func evalCondition(condition string, input *InputBag) (bool, error) {
tokens, err := condTokenize(condition)
if err != nil {
return false, err
}
p := &condParser{tokens: tokens, input: input}
result, err := p.parseOr()
if err != nil {
return false, err
}
if tok := p.peek(); tok.kind != cTokEOF {
return false, fmt.Errorf("unexpected token %q", tok.val)
}
return result, nil
}