-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathquery.go
More file actions
4072 lines (3852 loc) · 121 KB
/
Copy pathquery.go
File metadata and controls
4072 lines (3852 loc) · 121 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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License 2.0.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/)
// Copyright 2026-Present Datadog, Inc.
package fastjq
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// opType represents the type of operation in the AST.
type opType int
const (
opIdentity opType = iota // .
opField // .foo
opDelete // del(.foo)
opPipe // expr | expr
opApply // expr[...], expr.foo — postfix application with original-input scope
opBind // expr as $x | body
opLabel // label $x | body
opBreakOp // break $x
opVar // $x
opReduce // reduce gen as $x (init; update)
opForeach // foreach gen as $x (init; update; extract?)
opWhile // while(cond; update)
opRepeat // repeat(expr)
opUntil // until(cond; next)
opDefScope // def f(...): body; expr
opCall // f / f(a; b)
opAssign // lhs = rhs
opUpdate // lhs |= rhs
opUpdateAlt // lhs //= rhs
opUpdateMath // lhs += rhs, -=, *=, /=, %=
opIndex // .[0], .[-1]
opIndexExpr // .[expr] dynamic index/key expression
opIterator // .[]
opRecursiveDescent // ..
opRecurse // recurse / recurse(f) / recurse(f; cond)
opWalk // walk(f)
opConstruct // {name, a: .foo}
opArrayConstruct // [.foo, .bar]
opLiteral // null, true, false, "string", 123
opCompare // ==, !=, <, <=, >, >=
opSelect // select(cond)
opAlternative // expr // expr
opTypeBuiltin // type builtin
opAnd // expr and expr
opOr // expr or expr
opNot // not
opNeg // -expr
opOptional // expr? — suppress errors from child expression
opEmpty // empty — produce zero outputs
opHas // has("key")
opIf // if cond then expr else expr end
opLength // length
opAbs // abs
opToEntries // to_entries
opFromEntries // from_entries
opAdd // add
opFlatten // flatten / flatten(n)
opSlice // .[n:m], .[:m], .[n:]
opPlus // expr + expr
opIndex1 // index(s) — first occurrence
opRIndex1 // rindex(s) — last occurrence
opIndicesN // indices(s) — all occurrences
opDebug // debug — print to stderr, pass through
opBase64 // @base64 — encode string to base64
opBase64D // @base64d — decode base64 string
opValues // values — stream non-null values of object/array
opIn // in(obj) — reverse membership test
opSplit // split("s")
opJoin // join("s")
opStrftime // strftime(fmt)
opStrfLocaltime // strflocaltime(fmt)
opStrptime // strptime(fmt)
opMktime // mktime
opGmtime // gmtime
opFromdate // fromdate
opTodate // todate / date (compat alias)
opNow // now
opToStream // tostream
opTruncateStream // truncate_stream(stream)
opFromStream // fromstream(stream)
opAsciiDowncase // ascii_downcase
opAsciiUpcase // ascii_upcase
opStartsWith // startswith("s")
opEndsWith // endswith("s")
opTrim // trim
opLtrim // ltrim
opRtrim // rtrim
opTrimStr // trimstr("s")
opLtrimStr // ltrimstr("s")
opRtrimStr // rtrimstr("s")
opHaveDecnum // have_decnum
opUTF8ByteLength // utf8bytelength
opReverse // reverse
opCombinations // combinations / combinations(n)
opPick // pick(path, ...)
opBsearch // bsearch(x)
opINBuiltin // IN(gen) / IN(lhs; rhs)
opINDEXBuiltin // INDEX(gen; key)
opJOINBuiltin // JOIN(index; key)
opPath // path(expr)
opKeys // keys
opKeysUnsorted // keys_unsorted
opBuiltins // builtins
opPaths // paths / paths(filter)
opGetPath // getpath(path)
opSetPath // setpath(path; value)
opDelPaths // delpaths(paths)
opAny // any / any(expr)
opAll // all / all(expr)
opFirst // first(expr)
opLast // last(expr)
opLimit // limit(n; expr)
opSkip // skip(n; expr)
opMinus // expr - expr
opMul // expr * expr
opDiv // expr / expr
opMod // expr % expr
opMin // min
opMax // max
opMinBy // min_by(f)
opMaxBy // max_by(f)
opURIEncode // @uri
opTry // try expr / try expr catch handler
opToJSON // tojson / @json
opFromJSON // fromjson
opToString // tostring
opToNumber // tonumber
opToBoolean // toboolean
opContains // contains(val) — recursive containment; optional=true for inside()
opFloor // floor
opCeil // ceil
opRound // round
opError // error — throw input as error
opGenerator // a, b — multi-output sequence; elems = exprs to run in order
opHTMLEncode // @html
opCSVEncode // @csv
opTSVEncode // @tsv
opShEncode // @sh
opURIDecode // @urid
// 1-arg floating-point math builtins — all zero-alloc, all take number input.
// Remaining deferred higher-arity numeric builtins such as atan(y; x) are still
// documented in docs/SYNTAX.md. pow/hypot/fma are now implemented.
opMathSqrt // sqrt
opMathFabs // fabs (absolute value of number; distinct from length)
opMathAtan // atan (1-arg: atan(x); 2-arg atan(y;x) not supported)
opMathLog // log (natural log)
opMathLog2 // log2
opMathLog10 // log10
opMathExp // exp (e^x)
opMathExp2 // exp2 (2^x)
opMathExp10 // exp10 (10^x; implemented as pow(10,x))
opMathCbrt // cbrt (cube root)
opMathLogb // logb (base-2 exponent)
opMathNearbyint // nearbyint (round; approximation: uses round-half-away-from-zero)
opMathJ0 // j0 (Bessel function of first kind, order 0)
opMathJ1 // j1 (Bessel function of first kind, order 1)
opMathSin // sin
opMathCos // cos
opMathTan // tan
opMathAsin // asin
opMathAcos // acos
opMathTgamma // tgamma (gamma function, Γ(x))
opMathLgamma // lgamma (log of absolute gamma, ln|Γ(x)|)
opStringInterp // "\(expr)" string interpolation; elems=expressions, segs=literal segments
opFormatTemplate // @html "...\(...)..." — format each interpolation inside a template string
opIsEmpty // isempty(expr) — true if expr produces no outputs
opNth // nth(n; gen) — nth output of gen (0-indexed); left=n, child=gen
// Regex operations (Go RE2 engine — linear time, pattern compiled once at Compile())
opTest // test(re) / test(re; flags) — 0 allocs via re.Match
opMatchRe // match(re) / match(re; flags) — 1 alloc on match (FindSubmatchIndex []int)
opCapture // capture(re) / capture(re; flags) — 1 alloc on match
opScan // scan(re) / scan(re; flags) — allocs per match (multi-output)
opSub // sub(re; "literal") — replace first match
opGSub // gsub(re; "literal") — replace all matches
// range — Tier 2 (1 alloc per generated value, proportional to output count)
opRange // range(n) / range(from;to) / range(from;to;step)
// left=from, right=to, child=step (nil → step 1)
// Sort / unique / group — Tier 2 (allocate O(n) index proportional to collection size)
opSort // sort
opSortBy // sort_by(f) — child=key function
opUnique // unique
opUniqueBy // unique_by(f) — child=key function
opGroupBy // group_by(f) — child=key function
opTranspose // transpose
opExplode // explode — string → array of Unicode codepoints (Tier 2)
opImplode // implode — array of codepoints → string (Tier 2)
// nan/infinite predicates
opIsNaN // isnan — true if input is NaN
opIsInfinite // isinfinite — true if input is ±Inf
opIsFinite // isfinite — true if finite and not NaN
opIsNormal // isnormal — true if non-zero, finite, not subnormal
opPow // pow(x; y) — left=x, right=y
opHypot // hypot(x; y) — left=x, right=y
opFMA // fma(x; y; z) — left=x, right=y, child=z
)
// cmpOperator is the comparison operator used in opCompare nodes.
type cmpOperator int
const (
cmpEq cmpOperator = iota // ==
cmpNeq // !=
cmpLt // <
cmpLe // <=
cmpGt // >
cmpGe // >=
)
type updateOperator int
const (
updatePlus updateOperator = iota
updateMinus
updateMul
updateDiv
updateMod
)
// pair represents a key-expression pair in object construction.
type pair struct {
key string
keyExpr *op
expr *op
}
// op is a node in the query AST.
type op struct {
typ opType
field string // for opField
name string // for opVar/opBind
fn *funcDef // for opDefScope
pattern *bindPattern // for opBind/opReduce/opForeach destructuring bindings
altPatterns []*bindPattern // for opBind: fallback binding targets joined by ?//
fields []op // for opDelete: list of field-access/index paths to delete
left *op // for opPipe, opCompare, opAlternative, opNth
right *op // for opPipe, opCompare, opAlternative
child *op // for opField chaining, opSelect condition, opIsEmpty, opNth body
extra *op // for opForeach: extract expression
format opType // for opFormatTemplate: formatter applied to each interpolation
index int // for opIndex: array index (negative = from end)
pairs []pair // for opConstruct: {key: expr} pairs
multiValuePairs bool // for opConstruct: true if any pair expr may produce >1 output
elems []*op // for opArrayConstruct, opStringInterp, opFormatTemplate: expressions
segs [][]byte // for opStringInterp/opFormatTemplate: literal segments between expressions
literal []byte // for opLiteral: raw JSON bytes
re *regexp.Regexp // for regex ops (opTest/opMatchRe/opCapture/opScan/opSub/opGSub)
cmpOp cmpOperator // for opCompare: comparison operator
updateOp updateOperator // for opUpdateMath
optional bool // for opField/opIndex/opIterator: suppress errors
}
type bindPatternKind int
const (
bindPatternVar bindPatternKind = iota
bindPatternArray
bindPatternObject
)
type bindPattern struct {
kind bindPatternKind
name string
elems []*bindPattern
fields []bindPatternField
}
type bindPatternField struct {
key string
bindName string
pattern *bindPattern
}
// parse compiles a jq query string into an AST.
func parse(query string) (*op, error) {
query = strings.TrimSpace(query)
if query == "" {
return nil, fmt.Errorf("empty query")
}
result, rest, err := parseGeneratorExpr(query)
if err != nil {
return nil, err
}
rest = strings.TrimSpace(rest)
if rest != "" {
return nil, fmt.Errorf("unexpected trailing input: %q", rest)
}
// Optimization: simplify identity pipes
result = simplify(result)
if err := validateVars(result, nil); err != nil {
return nil, err
}
if err := validateLabels(result, nil); err != nil {
return nil, err
}
if err := validateFuncs(result, nil, nil); err != nil {
return nil, err
}
return result, nil
}
// parsePipeExpr parses a pipe chain: expr | expr | ...
func parsePipeExpr(s string) (*op, string, error) {
result, rest, err := parseBindExpr(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
for strings.HasPrefix(rest, "|") {
rest = strings.TrimSpace(rest[1:])
right, remainder, err := parseBindExpr(rest)
if err != nil {
return nil, remainder, err
}
result = &op{typ: opPipe, left: result, right: right}
rest = strings.TrimSpace(remainder)
}
return result, rest, nil
}
// parseBindExpr parses `expr as $name | body`.
// The bound value is produced by expr, but body runs against the original input.
func parseBindExpr(s string) (*op, string, error) {
left, rest, err := parseAssignExpr(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if !(strings.HasPrefix(rest, "as") && (len(rest) == 2 || !isIdentChar(rest[2]))) {
return left, rest, nil
}
asRest := rest
rest = strings.TrimSpace(rest[2:])
name, pattern, remaining, ok, err := parseBindingTarget(rest)
if err != nil {
return nil, remaining, err
}
if !ok {
return left, asRest, nil
}
remaining = strings.TrimSpace(remaining)
primaryPattern := bindingPatternFromTarget(name, pattern)
var altPatterns []*bindPattern
for strings.HasPrefix(remaining, "?//") {
nextName, nextPattern, nextRemaining, nextOK, err := parseBindingTarget(strings.TrimSpace(remaining[3:]))
if err != nil {
return nil, nextRemaining, err
}
if !nextOK {
return nil, remaining, fmt.Errorf("expected binding target after ?//")
}
altPatterns = append(altPatterns, bindingPatternFromTarget(nextName, nextPattern))
remaining = strings.TrimSpace(nextRemaining)
}
if len(remaining) == 0 || remaining[0] != '|' {
return left, asRest, nil
}
body, rest, err := parseGeneratorExpr(remaining[1:])
if err != nil {
return nil, rest, err
}
return &op{typ: opBind, name: name, pattern: primaryPattern, altPatterns: altPatterns, left: left, right: body}, rest, nil
}
func bindingPatternFromTarget(name string, pattern *bindPattern) *bindPattern {
if pattern != nil {
return pattern
}
if name == "" {
return nil
}
return &bindPattern{kind: bindPatternVar, name: name}
}
func parseAssignExpr(s string) (*op, string, error) {
left, rest, err := parseExpr(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if !canStartAssignment(left) {
return left, rest, nil
}
switch {
case strings.HasPrefix(rest, "//="):
right, remaining, err := parseExpr(strings.TrimSpace(rest[3:]))
if err != nil {
return nil, remaining, err
}
return &op{typ: opUpdateAlt, left: left, right: right}, remaining, nil
case strings.HasPrefix(rest, "|="):
right, remaining, err := parseExpr(strings.TrimSpace(rest[2:]))
if err != nil {
return nil, remaining, err
}
return &op{typ: opUpdate, left: left, right: right}, remaining, nil
case strings.HasPrefix(rest, "+="):
return parseUpdateMathExpr(left, rest[2:], updatePlus)
case strings.HasPrefix(rest, "-="):
return parseUpdateMathExpr(left, rest[2:], updateMinus)
case strings.HasPrefix(rest, "*="):
return parseUpdateMathExpr(left, rest[2:], updateMul)
case strings.HasPrefix(rest, "/="):
return parseUpdateMathExpr(left, rest[2:], updateDiv)
case strings.HasPrefix(rest, "%="):
return parseUpdateMathExpr(left, rest[2:], updateMod)
case len(rest) > 0 && rest[0] == '=' && (len(rest) == 1 || rest[1] != '='):
right, remaining, err := parseExpr(strings.TrimSpace(rest[1:]))
if err != nil {
return nil, remaining, err
}
return &op{typ: opAssign, left: left, right: right}, remaining, nil
default:
return left, rest, nil
}
}
func parseUpdateMathExpr(left *op, s string, update updateOperator) (*op, string, error) {
right, remaining, err := parseExpr(strings.TrimSpace(s))
if err != nil {
return nil, remaining, err
}
return &op{typ: opUpdateMath, left: left, right: right, updateOp: update}, remaining, nil
}
func canStartAssignment(node *op) bool {
if node == nil {
return false
}
if containsUnsupportedAssignNode(node) {
return false
}
return true
}
func containsUnsupportedAssignNode(node *op) bool {
if node == nil {
return false
}
switch node.typ {
case opReduce, opForeach, opDefScope:
return true
case opIndexExpr:
return containsUnsupportedAssignNode(node.left) || containsUnsupportedAssignNode(node.child)
case opConstruct:
for _, p := range node.pairs {
if containsUnsupportedAssignNode(p.expr) {
return true
}
}
return false
case opArrayConstruct, opGenerator, opStringInterp, opFormatTemplate:
for _, elem := range node.elems {
if containsUnsupportedAssignNode(elem) {
return true
}
}
return false
default:
return containsUnsupportedAssignNode(node.left) || containsUnsupportedAssignNode(node.right) || containsUnsupportedAssignNode(node.child)
}
}
func parseLabelExpr(s string) (*op, string, error) {
s = strings.TrimSpace(s)
if len(s) == 0 || s[0] != '$' {
return nil, s, fmt.Errorf("expected label name after label")
}
name, rest := readIdentifier(s[1:])
if name == "" {
return nil, rest, fmt.Errorf("expected label name after label")
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != '|' {
return nil, rest, fmt.Errorf("expected '|' after label $%s", name)
}
body, rest, err := parseGeneratorExpr(rest[1:])
if err != nil {
return nil, rest, err
}
return &op{typ: opLabel, name: name, child: body}, rest, nil
}
func parseBreakExpr(s string) (*op, string, error) {
s = strings.TrimSpace(s)
if len(s) == 0 || s[0] != '$' {
return nil, s, fmt.Errorf("expected label name after break")
}
name, rest := readIdentifier(s[1:])
if name == "" {
return nil, rest, fmt.Errorf("expected label name after break")
}
return &op{typ: opBreakOp, name: name}, rest, nil
}
// parseGeneratorExpr parses generator syntax in contexts where commas produce
// multiple outputs and bind tighter than pipes. This matches jq's parsing for
// forms like `[a, b | f]`, which is `[(a, b) | f]`, not `[a, (b | f)]`.
func parseGeneratorExpr(s string) (*op, string, error) {
first, rest, err := parseGeneratorTerm(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
for strings.HasPrefix(rest, "|") {
rest = strings.TrimSpace(rest[1:])
right, remainder, err := parseGeneratorTerm(rest)
if err != nil {
return nil, remainder, err
}
first = &op{typ: opPipe, left: first, right: right}
rest = strings.TrimSpace(remainder)
}
return first, rest, nil
}
// parseGeneratorTerm parses a comma-separated generator term where each element
// is a regular expression operand. Returns a single op if there is only one
// element, or an opGenerator if there are multiple.
func parseGeneratorTerm(s string) (*op, string, error) {
first, rest, err := parseBindExpr(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != ',' {
return first, rest, nil
}
elems := []*op{first}
for len(rest) > 0 && rest[0] == ',' {
rest = strings.TrimSpace(rest[1:])
next, rest2, err := parseBindExpr(rest)
if err != nil {
return nil, rest2, err
}
elems = append(elems, next)
rest = strings.TrimSpace(rest2)
}
return &op{typ: opGenerator, elems: elems}, rest, nil
}
// parseExpr parses a single expression at the lowest precedence level.
// Precedence chain: parseExpr → parseAlt → parseCmp → parseAtom
func parseExpr(s string) (*op, string, error) {
return parseAlt(s)
}
// parseAlt parses alternative expressions: expr // expr // ...
// Left-associative. Delegates down to parseOr.
func parseAlt(s string) (*op, string, error) {
left, rest, err := parseOr(s)
if err != nil {
return nil, rest, err
}
for {
rest = strings.TrimSpace(rest)
if len(rest) >= 2 && rest[0] == '/' && rest[1] == '/' {
if len(rest) >= 3 && rest[2] == '=' {
break
}
rest = strings.TrimSpace(rest[2:])
right, remainder, err := parseCmp(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: opAlternative, left: left, right: right}
rest = remainder
continue
}
break
}
return left, rest, nil
}
// parseOr parses: expr or expr or ...
// Left-associative. Delegates down to parseAnd.
func parseOr(s string) (*op, string, error) {
left, rest, err := parseAnd(s)
if err != nil {
return nil, rest, err
}
for {
rest = strings.TrimSpace(rest)
if len(rest) >= 2 && rest[0] == 'o' && rest[1] == 'r' && (len(rest) == 2 || !isIdentChar(rest[2])) {
rest = strings.TrimSpace(rest[2:])
right, remainder, err := parseAnd(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: opOr, left: left, right: right}
rest = remainder
continue
}
break
}
return left, rest, nil
}
// parseAnd parses: expr and expr and ...
// Left-associative. Delegates down to parseCmp.
func parseAnd(s string) (*op, string, error) {
left, rest, err := parseCmp(s)
if err != nil {
return nil, rest, err
}
for {
rest = strings.TrimSpace(rest)
if len(rest) >= 3 && rest[0] == 'a' && rest[1] == 'n' && rest[2] == 'd' && (len(rest) == 3 || !isIdentChar(rest[3])) {
rest = strings.TrimSpace(rest[3:])
right, remainder, err := parseCmp(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: opAnd, left: left, right: right}
rest = remainder
continue
}
break
}
return left, rest, nil
}
// parseAddExpr parses additive expressions: expr + expr, expr - expr (left-associative).
// Delegates down to parseMulExpr.
func parseAddExpr(s string) (*op, string, error) {
left, rest, err := parseMulExpr(s)
if err != nil {
return nil, rest, err
}
for {
rest = strings.TrimSpace(rest)
if len(rest) > 0 && rest[0] == '+' {
if len(rest) > 1 && rest[1] == '=' {
break
}
rest = strings.TrimSpace(rest[1:])
right, remainder, err := parseMulExpr(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: opPlus, left: left, right: right}
rest = remainder
continue
}
if len(rest) > 0 && rest[0] == '-' {
if len(rest) > 1 && rest[1] == '=' {
break
}
rest = strings.TrimSpace(rest[1:])
right, remainder, err := parseMulExpr(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: opMinus, left: left, right: right}
rest = remainder
continue
}
break
}
return left, rest, nil
}
// parseUnaryExpr parses prefix unary operators such as -expr.
// Delegates down to parseAtom.
func parseUnaryExpr(s string) (*op, string, error) {
s = strings.TrimSpace(s)
if len(s) > 0 && s[0] == '-' {
if strings.HasPrefix(s, "-nan") && (len(s) == 4 || !isIdentChar(s[4])) {
return parseAtom(s)
}
if strings.HasPrefix(s, "-infinite") && (len(s) == 9 || !isIdentChar(s[9])) {
return parseAtom(s)
}
if len(s) == 1 || !isDigit(s[1]) {
right, rest, err := parseUnaryExpr(s[1:])
if err != nil {
return nil, rest, err
}
return &op{typ: opNeg, child: right}, rest, nil
}
}
return parseAtom(s)
}
// parseMulExpr parses multiplicative expressions: expr * expr, expr / expr, expr % expr (left-associative).
// Delegates down to parseUnaryExpr.
func parseMulExpr(s string) (*op, string, error) {
left, rest, err := parseUnaryExpr(s)
if err != nil {
return nil, rest, err
}
for {
rest = strings.TrimSpace(rest)
var typ opType
if len(rest) > 0 && rest[0] == '*' {
if len(rest) > 1 && rest[1] == '=' {
break
}
typ = opMul
} else if len(rest) > 0 && rest[0] == '/' && !(len(rest) >= 2 && (rest[1] == '/' || rest[1] == '=')) {
typ = opDiv
} else if len(rest) > 0 && rest[0] == '%' {
if len(rest) > 1 && rest[1] == '=' {
break
}
typ = opMod
} else {
break
}
rest = strings.TrimSpace(rest[1:])
right, remainder, err := parseUnaryExpr(rest)
if err != nil {
return nil, remainder, err
}
left = &op{typ: typ, left: left, right: right}
rest = remainder
}
return left, rest, nil
}
// parseCmp parses comparison expressions: ==, !=, <, <=, >, >=
// Non-associative (no chaining). Delegates down to parseAddExpr.
func parseCmp(s string) (*op, string, error) {
left, rest, err := parseAddExpr(s)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
var operator cmpOperator
var advance int
switch {
case len(rest) >= 2 && rest[0] == '=' && rest[1] == '=':
operator, advance = cmpEq, 2
case len(rest) >= 2 && rest[0] == '!' && rest[1] == '=':
operator, advance = cmpNeq, 2
case len(rest) >= 2 && rest[0] == '<' && rest[1] == '=':
operator, advance = cmpLe, 2
case len(rest) >= 2 && rest[0] == '>' && rest[1] == '=':
operator, advance = cmpGe, 2
case len(rest) >= 1 && rest[0] == '<':
operator, advance = cmpLt, 1
case len(rest) >= 1 && rest[0] == '>':
operator, advance = cmpGt, 1
}
if advance == 0 {
return left, rest, nil
}
rest = strings.TrimSpace(rest[advance:])
right, remainder, err := parseAtom(rest)
if err != nil {
return nil, remainder, err
}
return &op{typ: opCompare, left: left, right: right, cmpOp: operator}, remainder, nil
}
// parseAtom parses a single atomic expression (not including pipe, alternative, or comparison).
func parseAtom(s string) (*op, string, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, "", fmt.Errorf("unexpected end of expression")
}
// String literal
if s[0] == '"' {
return parseStringLiteral(s)
}
// Variable reference: $name
if s[0] == '$' {
return parseVarRef(s)
}
if strings.HasPrefix(s, "break") && (len(s) == 5 || !isIdentChar(s[5])) {
return parseBreakExpr(s[5:])
}
if strings.HasPrefix(s, "def") && (len(s) == 3 || !isIdentChar(s[3])) {
return parseDefExpr(s[3:])
}
// del()
if strings.HasPrefix(s, "del(") {
return parseDel(s)
}
// select()
if strings.HasPrefix(s, "select(") {
return parseSelect(s)
}
if strings.HasPrefix(s, "walk(") {
node, rest, err := parseUnaryGenBuiltin(s[5:], opWalk)
if err != nil {
return nil, rest, err
}
return applyPostfixPipe(node, rest)
}
if strings.HasPrefix(s, "recurse") && (len(s) == 7 || !isIdentChar(s[7])) {
rest := strings.TrimSpace(s[7:])
if len(rest) > 0 && rest[0] == '(' {
node, tail, err := parseRecurse(rest[1:])
if err != nil {
return nil, tail, err
}
return applyPostfixPipe(node, tail)
}
return applyPostfixPipe(&op{typ: opRecurse}, rest)
}
// null literal (with boundary check)
if strings.HasPrefix(s, "null") && (len(s) == 4 || !isIdentChar(s[4])) {
return &op{typ: opLiteral, literal: []byte("null")}, s[4:], nil
}
// true literal (with boundary check)
if strings.HasPrefix(s, "true") && (len(s) == 4 || !isIdentChar(s[4])) {
return &op{typ: opLiteral, literal: []byte("true")}, s[4:], nil
}
// false literal (with boundary check)
if strings.HasPrefix(s, "false") && (len(s) == 5 || !isIdentChar(s[5])) {
return &op{typ: opLiteral, literal: []byte("false")}, s[5:], nil
}
// try / try-catch
if strings.HasPrefix(s, "try") && (len(s) == 3 || !isIdentChar(s[3])) {
return parseTry(s[3:])
}
if strings.HasPrefix(s, "label") && (len(s) == 5 || !isIdentChar(s[5])) {
return parseLabelExpr(s[5:])
}
// if-then-else
if strings.HasPrefix(s, "if") && (len(s) == 2 || !isIdentChar(s[2])) {
node, rest, err := parseIf(s)
if err != nil {
return nil, rest, err
}
return applyPostfixPipe(node, rest)
}
// empty — produce zero outputs
if strings.HasPrefix(s, "empty") && (len(s) == 5 || !isIdentChar(s[5])) {
return &op{typ: opEmpty}, s[5:], nil
}
// has("key")
if strings.HasPrefix(s, "has(") {
return parseHas(s)
}
// length builtin
if strings.HasPrefix(s, "length") && (len(s) == 6 || !isIdentChar(s[6])) {
return &op{typ: opLength}, s[6:], nil
}
if strings.HasPrefix(s, "abs") && (len(s) == 3 || !isIdentChar(s[3])) {
return &op{typ: opAbs}, s[3:], nil
}
// first / last — no-arg desugar to .[0] / .[-1]; with arg use dedicated op
if strings.HasPrefix(s, "first") && (len(s) == 5 || !isIdentChar(s[5])) {
rest := strings.TrimSpace(s[5:])
if len(rest) > 0 && rest[0] == '(' {
inner, rest2, err := parseGeneratorExpr(rest[1:])
if err != nil {
return nil, rest2, err
}
rest2 = strings.TrimSpace(rest2)
if len(rest2) == 0 || rest2[0] != ')' {
return nil, rest2, fmt.Errorf("expected ')' after first() argument")
}
return &op{typ: opFirst, child: inner}, rest2[1:], nil
}
return &op{typ: opIndex, index: 0}, rest, nil // first → .[0]
}
if strings.HasPrefix(s, "last") && (len(s) == 4 || !isIdentChar(s[4])) {
rest := strings.TrimSpace(s[4:])
if len(rest) > 0 && rest[0] == '(' {
inner, rest2, err := parseGeneratorExpr(rest[1:])
if err != nil {
return nil, rest2, err
}
rest2 = strings.TrimSpace(rest2)
if len(rest2) == 0 || rest2[0] != ')' {
return nil, rest2, fmt.Errorf("expected ')' after last() argument")
}
return &op{typ: opLast, child: inner}, rest2[1:], nil
}
return &op{typ: opIndex, index: -1}, rest, nil // last → .[-1]
}
// limit(n; expr) — body can be a comma-separated generator: limit(1; a, b)
if strings.HasPrefix(s, "limit(") {
nExpr, rest, err := parseGeneratorExpr(s[6:])
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != ';' {
return nil, rest, fmt.Errorf("expected ';' in limit(n; expr)")
}
rest = strings.TrimSpace(rest[1:])
genExpr, rest, err := parseGeneratorExpr(rest)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != ')' {
return nil, rest, fmt.Errorf("expected ')' after limit() arguments")
}
limits := make([]*op, 0, len(generatorElems(nExpr)))
for _, countExpr := range generatorElems(nExpr) {
limits = append(limits, &op{typ: opLimit, left: countExpr, child: genExpr})
}
return collapseGeneratorNodes(limits), rest[1:], nil
}
if strings.HasPrefix(s, "skip(") {
nExpr, rest, err := parseGeneratorExpr(s[5:])
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != ';' {
return nil, rest, fmt.Errorf("expected ';' in skip(n; expr)")
}
rest = strings.TrimSpace(rest[1:])
genExpr, rest, err := parseGeneratorExpr(rest)
if err != nil {
return nil, rest, err
}
rest = strings.TrimSpace(rest)
if len(rest) == 0 || rest[0] != ')' {
return nil, rest, fmt.Errorf("expected ')' after skip() arguments")
}
return &op{typ: opSkip, left: nExpr, child: genExpr}, rest[1:], nil
}
// keys / keys_unsorted
if strings.HasPrefix(s, "keys") && (len(s) == 4 || !isIdentChar(s[4])) {
return applyPostfixPipe(&op{typ: opKeys}, s[4:])
}
if strings.HasPrefix(s, "keys_unsorted") && (len(s) == 13 || !isIdentChar(s[13])) {
return applyPostfixPipe(&op{typ: opKeysUnsorted}, s[13:])
}
if strings.HasPrefix(s, "builtins") && (len(s) == 8 || !isIdentChar(s[8])) {
return applyPostfixPipe(&op{typ: opBuiltins}, s[8:])
}
if strings.HasPrefix(s, "have_decnum") && (len(s) == 11 || !isIdentChar(s[11])) {
return &op{typ: opHaveDecnum}, s[11:], nil
}
if strings.HasPrefix(s, "path(") {
node, rest, err := parseUnaryExprBuiltin(s[5:], opPath)
if err != nil {
return nil, rest, err
}
return applyPostfixPipe(node, rest)
}
if strings.HasPrefix(s, "leaf_paths") && (len(s) == 10 || !isIdentChar(s[10])) {
mkTypeNeq := func(t string) *op {
return &op{
typ: opCompare,
left: &op{typ: opTypeBuiltin},
right: &op{
typ: opLiteral,
literal: []byte(`"` + t + `"`),
},
cmpOp: cmpNeq,
}
}
cond := &op{typ: opAnd, left: mkTypeNeq("array"), right: mkTypeNeq("object")}
return &op{typ: opPaths, child: &op{typ: opSelect, child: cond}}, s[10:], nil
}
if strings.HasPrefix(s, "paths") && (len(s) == 5 || !isIdentChar(s[5])) {
rest := strings.TrimSpace(s[5:])
if len(rest) == 0 || rest[0] != '(' {
return &op{typ: opPaths}, rest, nil
}
return parseUnaryExprBuiltin(rest[1:], opPaths)
}
if strings.HasPrefix(s, "getpath(") {
return parseUnaryGenBuiltin(s[8:], opGetPath)
}
if strings.HasPrefix(s, "setpath(") {
pathExpr, rest, err := parsePipeExpr(s[8:])
if err != nil {
return nil, rest, err