forked from RecoLabs/gnata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc_fast.go
More file actions
424 lines (393 loc) · 11.3 KB
/
func_fast.go
File metadata and controls
424 lines (393 loc) · 11.3 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
package gnata
import (
"encoding/json"
"math"
"slices"
"strconv"
"strings"
"unicode/utf8"
"github.com/rbbydotdev/gnata-sqlite/internal/evaluator"
"github.com/rbbydotdev/gnata-sqlite/internal/parser"
"github.com/tidwall/gjson"
)
func isJSONArray(r *gjson.Result) bool {
return r.Type == gjson.JSON && r.Raw != "" && r.Raw[0] == '['
}
func isJSONObject(r *gjson.Result) bool {
return r.Type == gjson.JSON && r.Raw != "" && r.Raw[0] == '{'
}
// collectNumbers extracts all numeric values from a JSON array result.
// Returns (numbers, true) if all elements are numbers, or (nil, false)
// if any non-number element is found.
func collectNumbers(r *gjson.Result) ([]float64, bool) {
arr := r.Array()
nums := make([]float64, 0, len(arr))
for _, elem := range arr {
if elem.Type != gjson.Number {
return nil, false
}
nums = append(nums, elem.Float())
}
return nums, true
}
// funcFastHandler evaluates a fast-path function against a resolved gjson.Result.
// Returns (result, handled, error).
type funcFastHandler func(r *gjson.Result, f *parser.FuncFastPath) (any, bool, error)
// funcFastHandlers maps each FuncFastKind to its handler. Using a dispatch map
// instead of a giant switch keeps per-handler complexity low and avoids exhaustive
// lint violations on the FuncFastKind enum (new kinds that aren't ready for fast-path
// simply fall through to full evaluation).
// Note: FuncFastRound is intentionally absent — it requires banker's rounding
// which the full evaluator handles correctly.
var funcFastHandlers = map[parser.FuncFastKind]funcFastHandler{
parser.FuncFastExists: evalFuncExists,
parser.FuncFastContains: evalFuncContains,
parser.FuncFastString: evalFuncString,
parser.FuncFastBoolean: evalFuncBoolean,
parser.FuncFastNumber: evalFuncNumber,
parser.FuncFastKeys: evalFuncKeys,
parser.FuncFastDistinct: evalFuncDistinct,
parser.FuncFastNot: evalFuncNot,
parser.FuncFastLowercase: evalFuncLowercase,
parser.FuncFastUppercase: evalFuncUppercase,
parser.FuncFastTrim: evalFuncTrim,
parser.FuncFastLength: evalFuncLength,
parser.FuncFastType: evalFuncType,
parser.FuncFastAbs: evalFuncAbs,
parser.FuncFastFloor: evalFuncFloor,
parser.FuncFastCeil: evalFuncCeil,
parser.FuncFastSqrt: evalFuncSqrt,
parser.FuncFastCount: evalFuncCount,
parser.FuncFastReverse: evalFuncReverse,
parser.FuncFastSum: evalFuncSum,
parser.FuncFastMax: evalFuncMax,
parser.FuncFastMin: evalFuncMin,
parser.FuncFastAverage: evalFuncAverage,
}
func evalFunc(f *parser.FuncFastPath, data json.RawMessage, mapData map[string]json.RawMessage) (result any, handled bool, err error) {
r := resolveGjsonPath(data, mapData, f.Path)
if !r.Exists() {
// Fall through to full evaluator — gjson doesn't auto-map through
// arrays, so the path might still resolve via the AST walker.
return nil, false, nil
}
if h, ok := funcFastHandlers[f.Kind]; ok {
return h(&r, f)
}
return nil, false, nil
}
func evalFuncExists(_ *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
return true, true, nil
}
func evalFuncContains(r *gjson.Result, f *parser.FuncFastPath) (result any, handled bool, err error) {
//nolint:exhaustive // only handle types relevant to this fast path
switch r.Type {
case gjson.String:
return strings.Contains(r.Str, f.StrArg), true, nil
case gjson.JSON:
if isJSONArray(r) {
found := false
r.ForEach(func(_, elem gjson.Result) bool {
if elem.Type == gjson.String && strings.Contains(elem.Str, f.StrArg) {
found = true
return false
}
return true
})
return found, true, nil
}
return nil, false, nil
default:
return nil, false, nil
}
}
func evalFuncString(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
switch r.Type {
case gjson.String:
return r.Str, true, nil
case gjson.Number:
return evaluator.FormatNumber(json.Number(r.Raw)), true, nil
case gjson.True:
return "true", true, nil
case gjson.False:
return "false", true, nil
case gjson.Null:
return parser.NullJSON, true, nil
case gjson.JSON:
return nil, false, nil
default:
return nil, false, nil
}
}
func evalFuncBoolean(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
switch r.Type {
case gjson.True:
return true, true, nil
case gjson.False:
return false, true, nil
case gjson.Null:
return false, true, nil
case gjson.String:
return r.Str != "", true, nil
case gjson.Number:
return r.Float() != 0, true, nil
case gjson.JSON:
return nil, false, nil
default:
return nil, false, nil
}
}
func evalFuncNumber(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
//nolint:exhaustive // only handle types relevant to this fast path
switch r.Type {
case gjson.Number:
return r.Float(), true, nil
case gjson.String:
v, parseErr := strconv.ParseFloat(r.Str, 64)
if parseErr != nil || math.IsInf(v, 0) || math.IsNaN(v) {
// Fall through to full evaluator on parse failure or non-finite value.
return nil, false, nil //nolint:nilerr // intentional: signal fallback, not a real error
}
return v, true, nil
case gjson.True:
return float64(1), true, nil
case gjson.False:
return float64(0), true, nil
default:
return nil, false, nil
}
}
func evalFuncKeys(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONObject(r) {
var keys []any
r.ForEach(func(key, _ gjson.Result) bool {
keys = append(keys, key.String())
return true
})
switch len(keys) {
case 0:
return nil, true, nil
case 1:
return keys[0], true, nil
default:
return keys, true, nil
}
}
return nil, false, nil
}
func evalFuncDistinct(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
seen := map[string]struct{}{}
out := make([]any, 0)
hasComplex := false
inputLen := 0
r.ForEach(func(_, elem gjson.Result) bool {
inputLen++
var key string
//nolint:exhaustive // only handle scalar types; complex types fall through
switch elem.Type {
case gjson.Number:
key = strconv.FormatFloat(elem.Float(), 'f', -1, 64)
case gjson.String:
key = "s:" + elem.Str
case gjson.True:
key = "b:true"
case gjson.False:
key = "b:false"
case gjson.Null:
key = parser.NullJSON
default:
hasComplex = true
return false
}
if _, dup := seen[key]; !dup {
seen[key] = struct{}{}
out = append(out, gjsonValueToAny(&elem))
}
return true
})
if hasComplex {
return nil, false, nil
}
// Singleton unwrap: mirrors *Sequence + CollapseSequence in the full
// evaluator path. inputLen > 1 corresponds to the len(arr) <= 1
// early-return guard in fnDistinct that skips Sequence wrapping
// when no dedup was needed.
if len(out) == 1 && inputLen > 1 {
return out[0], true, nil
}
return out, true, nil
}
return nil, false, nil
}
func evalFuncNot(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
switch r.Type {
case gjson.True:
return false, true, nil
case gjson.False:
return true, true, nil
case gjson.Null:
return true, true, nil
case gjson.String:
return r.Str == "", true, nil
case gjson.Number:
return r.Float() == 0, true, nil
case gjson.JSON:
return nil, false, nil
default:
return nil, false, nil
}
}
func evalFuncLowercase(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.String {
return strings.ToLower(r.Str), true, nil
}
return nil, false, nil
}
func evalFuncUppercase(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.String {
return strings.ToUpper(r.Str), true, nil
}
return nil, false, nil
}
func evalFuncTrim(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.String {
return strings.Join(strings.Fields(r.Str), " "), true, nil
}
return nil, false, nil
}
func evalFuncLength(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.String {
return float64(utf8.RuneCountInString(r.Str)), true, nil
}
return nil, false, nil
}
func evalFuncType(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
switch r.Type {
case gjson.String:
return "string", true, nil
case gjson.Number:
return "number", true, nil
case gjson.True, gjson.False:
return "boolean", true, nil
case gjson.Null:
return parser.NullJSON, true, nil
case gjson.JSON:
if r.Raw != "" {
switch r.Raw[0] {
case '[':
return "array", true, nil
case '{':
return "object", true, nil
}
}
return nil, false, nil
default:
return nil, false, nil
}
}
func evalFuncAbs(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.Number {
return math.Abs(r.Float()), true, nil
}
return nil, false, nil
}
func evalFuncFloor(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.Number {
return math.Floor(r.Float()), true, nil
}
return nil, false, nil
}
func evalFuncCeil(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.Number {
return math.Ceil(r.Float()), true, nil
}
return nil, false, nil
}
func evalFuncSqrt(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if r.Type == gjson.Number {
v := r.Float()
if v < 0 {
return nil, false, nil
}
return math.Sqrt(v), true, nil
}
return nil, false, nil
}
func evalFuncCount(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
count := 0
r.ForEach(func(_, _ gjson.Result) bool {
count++
return true
})
return float64(count), true, nil
}
return float64(1), true, nil
}
func evalFuncReverse(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
elems := make([]any, 0)
r.ForEach(func(_, elem gjson.Result) bool {
elems = append(elems, gjsonValueToAny(&elem))
return true
})
slices.Reverse(elems)
return elems, true, nil
}
return nil, false, nil
}
func evalFuncSum(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
nums, ok := collectNumbers(r)
if !ok {
return nil, false, nil
}
sum := 0.0
for _, n := range nums {
sum += n
}
return sum, true, nil
}
return nil, false, nil
}
func evalFuncMax(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
nums, ok := collectNumbers(r)
if !ok {
return nil, false, nil
}
if len(nums) == 0 {
return nil, true, nil
}
return slices.Max(nums), true, nil
}
return nil, false, nil
}
func evalFuncMin(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
nums, ok := collectNumbers(r)
if !ok {
return nil, false, nil
}
if len(nums) == 0 {
return nil, true, nil
}
return slices.Min(nums), true, nil
}
return nil, false, nil
}
func evalFuncAverage(r *gjson.Result, _ *parser.FuncFastPath) (result any, handled bool, err error) {
if isJSONArray(r) {
nums, ok := collectNumbers(r)
if !ok || len(nums) == 0 {
return nil, false, nil
}
sum := 0.0
for _, n := range nums {
sum += n
}
return sum / float64(len(nums)), true, nil
}
return nil, false, nil
}