Repository navigation
Expand file tree
/
Copy patheval.go
More file actions
431 lines (413 loc) · 10.6 KB
/
Copy patheval.go
File metadata and controls
431 lines (413 loc) · 10.6 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
package validator
import (
"context"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"github.com/libtnb/validator/conv"
)
// This file is the evaluation engine. A compiledField runs in two modes:
// evalCompiledField collects diagnostics for Validate, and fieldPasses
// answers Valid's yes/no without allocating. Both take a pooled Field, honor
// "sometimes" absence, run the container rules on the filtered value, then
// dive into each element of the raw collection. Dive elements are probed
// with the fast path first so the "field[i]" key is built only for failures,
// and map elements get deterministic labels. Rule and reflection panics are
// recovered into *RuleError.
var fieldPool = sync.Pool{New: func() any { return &Field{} }}
// evalCompiledField appends the field's failures to dst. Reflection panics
// become execution errors.
func (vd *Validation) evalCompiledField(
ctx context.Context,
cf compiledField,
dst []FieldError,
) (out []FieldError, err error) {
if err := context.Cause(ctx); err != nil {
return dst, err
}
out = dst
defer func() {
if recovered := recover(); recovered != nil {
// conv.ToString, not %v: a panic value whose String() panics must not re-escape recovery
err = &RuleError{Field: cf.name, Err: fmt.Errorf("%w: %s", ErrRulePanic, conv.ToString(recovered))}
}
}()
if cf.buildErr != nil {
return dst, &RulesError{Field: cf.name, Err: cf.buildErr}
}
if vd.sometimesAbsent(cf) {
return out, nil
}
if cf.container != nil {
cval := vd.containerValue(cf)
if cf.hasDive {
cval = vd.rawValue(cf)
}
out, err = vd.evalCompiled(
ctx,
cf.name,
cf.name,
cf.container,
cval,
out,
)
if err != nil {
return out, err
}
}
if cf.hasDive && cf.element != nil {
// dive uses the raw collection; filtering would stringify it.
out, err = vd.evalDive(
ctx,
cf.name,
cf.element,
vd.rawValue(cf),
out,
)
}
return out, err
}
// sometimesAbsent reports whether a "sometimes" field is skipped; the source
// decides what absence means (a missing map key, a nil struct pointer).
func (vd *Validation) sometimesAbsent(cf compiledField) bool {
if cf.container == nil || !cf.container.sometimes {
return false
}
return vd.src.absent(cf.name)
}
// rawValue reads the field before filters. A struct plan carries the index
// path, which skips the by-name lookup.
func (vd *Validation) rawValue(cf compiledField) reflect.Value {
if cf.index != nil {
return vd.ss.byIndex(cf.index)
}
v, _ := vd.srcLookup(cf.name)
return v
}
func (vd *Validation) containerValue(cf compiledField) reflect.Value {
if vd.filtered != nil {
if fv, ok := vd.filtered[cf.name]; ok {
return toValue(fv)
}
}
return vd.rawValue(cf)
}
func (vd *Validation) diag(field, msg string) FieldError {
return FieldError{Field: field, Message: msg}
}
// evalCompiled runs one compiled program in diagnostic mode over a pooled
// Field; rule panics become execution errors. name is the error key; scope
// is the cross-field identity (the container name for dive elements) so
// sibling resolution matches the fast path exactly.
func (vd *Validation) evalCompiled(
ctx context.Context,
name string,
scope string,
compiled *compiled,
val reflect.Value,
dst []FieldError,
) (out []FieldError, err error) {
f := fieldPool.Get().(*Field)
f.name, f.scope, f.rv, f.ctx, f.vd = name, scope, val, ctx, vd
out = dst
defer func() {
*f = Field{}
fieldPool.Put(f)
if recovered := recover(); recovered != nil {
// conv.ToString, not %v: see evalCompiledField
err = &RuleError{Field: name, Err: fmt.Errorf("%w: %s", ErrRulePanic, conv.ToString(recovered))}
}
}()
_, out, err = compiled.Diag(f, dst)
return out, err
}
func (vd *Validation) evalDive(
ctx context.Context,
name string,
element *compiled,
val reflect.Value,
dst []FieldError,
) ([]FieldError, error) {
// val is pre-unwrapped; invalid Value means nil container.
if !val.IsValid() {
return dst, nil
}
switch val.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < val.Len(); i++ {
// unwrap so rules see the pointee, matching every source
ev := unwrapValue(val.Index(i))
// fast probe first: the "field[i]" key is built only for a failing
// element; custom rules must be deterministic.
passes, err := vd.exprPasses(
ctx,
name,
element,
ev,
)
if err != nil {
return dst, err
}
if passes {
continue
}
dst, err = vd.evalCompiled(
ctx,
name+"["+strconv.Itoa(i)+"]",
name,
element,
ev,
dst,
)
if err != nil {
return dst, err
}
}
case reflect.Map:
return vd.evalDiveMap(
ctx,
name,
element,
val,
dst,
)
default:
// non-collection: fail-closed if non-empty, else skip (omitempty)
if !IsEmptyValue(val) {
dst = append(dst, vd.diag(name, "validator: dive requires an array or map value"))
}
}
return dst, nil
}
// evalDiveMap dives into a map. MapRange avoids MapIndex with NaN keys; type
// and ordinal suffixes keep rendered key collisions distinct.
func (vd *Validation) evalDiveMap(
ctx context.Context,
name string,
element *compiled,
rv reflect.Value,
dst []FieldError,
) ([]FieldError, error) {
type mentry struct {
mapKeyOrder
val reflect.Value
}
// Fast probe each entry first: the label machinery (stringify/sort/dedup)
// runs only over failing entries, and only those need unique error keys.
var failed []mentry
for it := rv.MapRange(); it.Next(); {
// unwrap so rules see the pointee, matching every source
ev := unwrapValue(it.Value())
passes, err := vd.exprPasses(
ctx,
name,
element,
ev,
)
if err != nil {
return dst, err
}
if passes {
continue
}
failed = append(failed, mentry{mapKeyOrder: mapKeyOrderOf(it.Key(), it.Value()), val: ev})
}
labels := mapFailureLabels(failed)
for i, e := range failed {
var err error
dst, err = vd.evalCompiled(
ctx,
name+"["+labels[i]+"]",
name,
element,
e.val,
dst,
)
if err != nil {
return dst, err
}
}
return dst, nil
}
// mapKeyOrderOf renders a map entry for deterministic ordering and labels;
// the value may be cyclic, so it uses cycle-bounded conv.ToString.
func mapKeyOrderOf(k, v reflect.Value) mapKeyOrder {
return mapKeyOrder{
keyRepr: fmt.Sprintf("%v", k.Interface()),
keyType: dynType(k).String(),
valRepr: conv.ToString(v.Interface()),
valType: dynType(v).String(),
}
}
// mapFailureLabels sorts failing map entries into a total order and returns
// their unique error labels in that order: the rendered key, qualified by its
// type when two keys render alike and numbered when still equal. The total
// order makes labels independent of map iteration; only entries equal in all
// four fields (NaN keys) stay unordered.
func mapFailureLabels[E interface{ keyOrder() mapKeyOrder }](failed []E) []string {
if len(failed) == 0 {
return nil
}
sort.SliceStable(failed, func(a, b int) bool { return failed[a].keyOrder().less(failed[b].keyOrder()) })
formatCount := make(map[string]int, len(failed))
for i := range failed {
formatCount[failed[i].keyOrder().keyRepr]++
}
labels := make([]string, len(failed))
used := make(map[string]bool, len(failed))
for i := range failed {
order := failed[i].keyOrder()
display := order.keyRepr
if formatCount[order.keyRepr] > 1 {
display = order.keyRepr + "|" + order.keyType
}
label := display
for n := 1; used[label]; n++ {
label = fmt.Sprintf("%s#%d", display, n)
}
used[label] = true
labels[i] = label
}
return labels
}
// validFast is Valid's verdict-only pass: it stops at the first failing
// field and never builds error keys or messages.
func (vd *Validation) validFast(ctx context.Context) (ok bool, err error) {
if ctx == nil {
return false, ErrNilContext
}
if err := context.Cause(ctx); err != nil {
return false, err
}
// Fail closed on any rule/dive panic. Valid() attaches the struct plan's
// rules snapshot and never filters, so the fast path carries no filters.
defer func() {
if recovered := recover(); recovered != nil {
ok = false
err = &RuleError{Err: fmt.Errorf("%w: %s", ErrRulePanic, conv.ToString(recovered))}
}
}()
if vd.rulesShared {
for i := range vd.plan {
passed, err := vd.fieldPasses(ctx, vd.plan[i])
if err != nil || !passed {
return false, err
}
}
} else {
// slow path (AddRules-mutated): split+compile per field on demand
for name, expr := range vd.rules {
if strings.TrimSpace(expr) == "" {
continue
}
passed, err := vd.fieldPasses(ctx, vd.validator.buildCompiledField(name, expr))
if err != nil || !passed {
return false, err
}
}
}
for _, ef := range vd.elemFields() {
passed, err := vd.elemFieldPasses(ctx, ef)
if err != nil || !passed {
return false, err
}
}
return true, nil
}
func (vd *Validation) fieldPasses(ctx context.Context, cf compiledField) (bool, error) {
if cf.buildErr != nil {
return false, &RulesError{Field: cf.name, Err: cf.buildErr}
}
if vd.sometimesAbsent(cf) {
return true, nil
}
if cf.container != nil {
cval := vd.containerValue(cf)
if cf.hasDive {
cval = vd.rawValue(cf)
}
passed, err := vd.exprPasses(
ctx,
cf.name,
cf.container,
cval,
)
if err != nil || !passed {
return false, err
}
}
if cf.hasDive && cf.element != nil {
passed, err := vd.divePasses(
ctx,
cf.name,
cf.element,
vd.rawValue(cf),
)
if err != nil || !passed {
return false, err
}
}
return true, nil
}
// exprPasses runs one compiled program in fast mode over a pooled Field;
// rule panics become execution errors.
func (vd *Validation) exprPasses(
ctx context.Context,
name string,
compiled *compiled,
val reflect.Value,
) (ok bool, err error) {
f := fieldPool.Get().(*Field)
f.name, f.scope, f.rv, f.ctx, f.vd = name, name, val, ctx, vd
defer func() {
*f = Field{}
fieldPool.Put(f)
if recovered := recover(); recovered != nil {
ok = false
err = &RuleError{Field: name, Err: fmt.Errorf("%w: %s", ErrRulePanic, conv.ToString(recovered))}
}
}()
return compiled.Fast(f)
}
func (vd *Validation) divePasses(
ctx context.Context,
name string,
element *compiled,
val reflect.Value,
) (bool, error) {
if !val.IsValid() {
return true, nil
}
switch val.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < val.Len(); i++ {
passed, err := vd.exprPasses(
ctx,
name,
element,
unwrapValue(val.Index(i)),
)
if err != nil || !passed {
return false, err
}
}
case reflect.Map:
for it := val.MapRange(); it.Next(); {
passed, err := vd.exprPasses(
ctx,
name,
element,
unwrapValue(it.Value()),
)
if err != nil || !passed {
return false, err
}
}
default:
return IsEmptyValue(val), nil
}
return true, nil
}