-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
5168 lines (4925 loc) · 157 KB
/
Copy pathparser.go
File metadata and controls
5168 lines (4925 loc) · 157 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
// Auto-generated LL(k) recursive-descent parser.
//
// Generated from protobuf specifications.
// Do not modify this file! If you need to modify the parser, edit the generator code
// in `meta/` or edit the protobuf specification in `proto/v1`.
//
// Command: python -m meta.cli ../proto/relationalai/lqp/v1/fragments.proto ../proto/relationalai/lqp/v1/logic.proto ../proto/relationalai/lqp/v1/transactions.proto --grammar src/meta/grammar.y --parser go
package lqp
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"math"
"math/big"
"reflect"
"regexp"
"strconv"
"strings"
pb "github.com/RelationalAI/logical-query-protocol/sdks/go/src/lqp/v1"
"google.golang.org/protobuf/reflect/protoreflect"
)
// Location represents a source location (1-based line/column, 0-based byte offset).
type Location struct {
Line int
Column int
Offset int
}
// Span represents a source span from start to stop location.
type Span struct {
Start Location
Stop Location
TypeName string
}
// ParseError represents a parse error
type ParseError struct {
msg string
}
func (e ParseError) Error() string {
return e.msg
}
func ptr[T any](v T) *T { return &v }
func deref[T any](p *T, d T) T {
if p != nil {
return *p
}
return d
}
// tokenKind discriminates which field of TokenValue is active.
type tokenKind int
const (
kindString tokenKind = iota
kindInt64
kindInt32
kindUint32
kindFloat64
kindFloat32
kindUint128
kindInt128
kindDecimal
)
// TokenValue holds a typed token value.
type TokenValue struct {
kind tokenKind
str string
i64 int64
i32 int32
u32 uint32
f64 float64
f32 float32
uint128 *pb.UInt128Value
int128 *pb.Int128Value
decimal *pb.DecimalValue
}
func (tv TokenValue) String() string {
switch tv.kind {
case kindInt64:
return strconv.FormatInt(tv.i64, 10)
case kindInt32:
return fmt.Sprintf("%di32", tv.i32)
case kindUint32:
return fmt.Sprintf("%du32", tv.u32)
case kindFloat64:
return strconv.FormatFloat(tv.f64, 'g', -1, 64)
case kindFloat32:
if math.IsInf(float64(tv.f32), 0) {
return "inf32"
}
if math.IsNaN(float64(tv.f32)) {
return "nan32"
}
return fmt.Sprintf("%sf32", strconv.FormatFloat(float64(tv.f32), 'g', -1, 32))
case kindUint128:
return fmt.Sprintf("0x%016x%016x", tv.uint128.High, tv.uint128.Low)
case kindInt128:
return fmt.Sprintf("%v", tv.int128)
case kindDecimal:
return fmt.Sprintf("%v", tv.decimal)
default:
return tv.str
}
}
// Token represents a lexer token
type Token struct {
Type string
Value TokenValue
StartPos int
EndPos int
}
// Pos returns the start position for backwards compatibility.
func (t Token) Pos() int { return t.StartPos }
func (t Token) String() string {
return fmt.Sprintf("Token(%s, %v, %d)", t.Type, t.Value, t.StartPos)
}
// tokenSpec represents a token specification for the lexer
type tokenSpec struct {
name string
regex *regexp.Regexp
action func(string) TokenValue
}
var (
whitespaceRe = regexp.MustCompile(`^\s+`)
commentRe = regexp.MustCompile(`^;;.*`)
tokenSpecs = []tokenSpec{
{"LITERAL", regexp.MustCompile(`^::`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^<=`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^>=`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\#`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\(`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\)`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\*`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\+`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\-`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^/`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^:`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^<`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^=`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^>`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\[`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\]`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\{`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\|`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"LITERAL", regexp.MustCompile(`^\}`), func(s string) TokenValue { return TokenValue{kind: kindString, str: s} }},
{"DECIMAL", regexp.MustCompile(`^[-]?\d+\.\d+d\d+`), func(s string) TokenValue { return TokenValue{kind: kindDecimal, decimal: scanDecimal(s)} }},
{"FLOAT32", regexp.MustCompile(`^([-]?\d+\.\d+f32|inf32|nan32)`), func(s string) TokenValue { return TokenValue{kind: kindFloat32, f32: scanFloat32(s)} }},
{"FLOAT", regexp.MustCompile(`^([-]?\d+\.\d+|inf|nan)`), func(s string) TokenValue { return TokenValue{kind: kindFloat64, f64: scanFloat(s)} }},
{"INT32", regexp.MustCompile(`^[-]?\d+i32`), func(s string) TokenValue { return TokenValue{kind: kindInt32, i32: scanInt32(s)} }},
{"INT", regexp.MustCompile(`^[-]?\d+`), func(s string) TokenValue { return TokenValue{kind: kindInt64, i64: scanInt(s)} }},
{"UINT32", regexp.MustCompile(`^\d+u32`), func(s string) TokenValue { return TokenValue{kind: kindUint32, u32: scanUint32(s)} }},
{"INT128", regexp.MustCompile(`^[-]?\d+i128`), func(s string) TokenValue { return TokenValue{kind: kindInt128, int128: scanInt128(s)} }},
{"STRING", regexp.MustCompile(`^"(?:[^"\\]|\\.)*"`), func(s string) TokenValue { return TokenValue{kind: kindString, str: scanString(s)} }},
{"SYMBOL", regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_.#/-]*`), func(s string) TokenValue { return TokenValue{kind: kindString, str: scanSymbol(s)} }},
{"UINT128", regexp.MustCompile(`^0x[0-9a-fA-F]+`), func(s string) TokenValue { return TokenValue{kind: kindUint128, uint128: scanUint128(s)} }},
}
)
// Lexer tokenizes input
type Lexer struct {
input string
pos int
tokens []Token
}
// NewLexer creates a new lexer and tokenizes the input
func NewLexer(input string) *Lexer {
l := &Lexer{
input: input,
pos: 0,
tokens: make([]Token, 0),
}
l.tokenize()
return l
}
func (l *Lexer) tokenize() {
for l.pos < len(l.input) {
remaining := l.input[l.pos:]
// Skip whitespace
if m := whitespaceRe.FindString(remaining); m != "" {
l.pos += len(m)
continue
}
// Skip comments
if m := commentRe.FindString(remaining); m != "" {
l.pos += len(m)
continue
}
// Collect all matching tokens
type candidate struct {
tokenType string
value string
action func(string) TokenValue
endPos int
}
var candidates []candidate
for _, spec := range tokenSpecs {
if loc := spec.regex.FindStringIndex(remaining); loc != nil && loc[0] == 0 {
value := remaining[:loc[1]]
candidates = append(candidates, candidate{
tokenType: spec.name,
value: value,
action: spec.action,
endPos: l.pos + loc[1],
})
}
}
if len(candidates) == 0 {
panic(ParseError{msg: fmt.Sprintf("Unexpected character at position %d: %q", l.pos, string(l.input[l.pos]))})
}
// Pick the longest match
best := candidates[0]
for _, c := range candidates[1:] {
if c.endPos > best.endPos {
best = c
}
}
l.tokens = append(l.tokens, Token{
Type: best.tokenType,
Value: best.action(best.value),
StartPos: l.pos,
EndPos: best.endPos,
})
l.pos = best.endPos
}
l.tokens = append(l.tokens, Token{Type: "$", Value: TokenValue{}, StartPos: l.pos, EndPos: l.pos})
}
// Scanner functions for each token type
func scanSymbol(s string) string {
return s
}
func scanString(s string) string {
unquoted, err := strconv.Unquote(s)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid string literal: %s", s)})
}
return unquoted
}
func scanInt(s string) int64 {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid integer: %s", s)})
}
return n
}
func scanInt32(s string) int32 {
numStr := s[:len(s)-3] // Remove "i32" suffix
n, err := strconv.ParseInt(numStr, 10, 32)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid int32: %s", s)})
}
return int32(n)
}
func scanUint32(s string) uint32 {
numStr := s[:len(s)-3] // Remove "u32" suffix
n, err := strconv.ParseUint(numStr, 10, 32)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid uint32: %s", s)})
}
return uint32(n)
}
func scanFloat32(s string) float32 {
if s == "inf32" {
return float32(math.Inf(1))
} else if s == "nan32" {
return float32(math.NaN())
}
numStr := s[:len(s)-3] // Remove "f32" suffix
f, err := strconv.ParseFloat(numStr, 32)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid float32: %s", s)})
}
return float32(f)
}
func scanFloat(s string) float64 {
if s == "inf" {
return math.Inf(1)
} else if s == "nan" {
return math.NaN()
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid float: %s", s)})
}
return f
}
func scanUint128(s string) *pb.UInt128Value {
hexStr := s[2:]
n := new(big.Int)
if _, ok := n.SetString(hexStr, 16); !ok {
panic(ParseError{msg: fmt.Sprintf("Invalid uint128: %s", s)})
}
mask := new(big.Int).SetUint64(0xFFFFFFFFFFFFFFFF)
low := new(big.Int).And(n, mask).Uint64()
high := new(big.Int).Rsh(n, 64).Uint64()
return &pb.UInt128Value{Low: low, High: high}
}
func scanInt128(s string) *pb.Int128Value {
numStr := s[:len(s)-4]
n := new(big.Int)
if _, ok := n.SetString(numStr, 10); !ok {
panic(ParseError{msg: fmt.Sprintf("Invalid int128: %s", s)})
}
var low, high uint64
if n.Sign() >= 0 {
mask := new(big.Int).SetUint64(0xFFFFFFFFFFFFFFFF)
low = new(big.Int).And(n, mask).Uint64()
high = new(big.Int).Rsh(n, 64).Uint64()
} else {
twoTo128 := new(big.Int).Lsh(big.NewInt(1), 128)
unsigned := new(big.Int).Add(n, twoTo128)
mask := new(big.Int).SetUint64(0xFFFFFFFFFFFFFFFF)
low = new(big.Int).And(unsigned, mask).Uint64()
high = new(big.Int).Rsh(unsigned, 64).Uint64()
}
return &pb.Int128Value{Low: low, High: high}
}
func scanDecimal(s string) *pb.DecimalValue {
parts := strings.Split(s, "d")
if len(parts) != 2 {
panic(ParseError{msg: fmt.Sprintf("Invalid decimal format: %s", s)})
}
decParts := strings.Split(parts[0], ".")
scale := int32(0)
if len(decParts) == 2 {
scale = int32(len(decParts[1]))
}
precision, err := strconv.ParseInt(parts[1], 10, 32)
if err != nil {
panic(ParseError{msg: fmt.Sprintf("Invalid decimal precision: %s", s)})
}
intStr := strings.ReplaceAll(parts[0], ".", "")
n := new(big.Int)
if _, ok := n.SetString(intStr, 10); !ok {
panic(ParseError{msg: fmt.Sprintf("Invalid decimal value: %s", s)})
}
var low, high uint64
if n.Sign() >= 0 {
mask := new(big.Int).SetUint64(0xFFFFFFFFFFFFFFFF)
low = new(big.Int).And(n, mask).Uint64()
high = new(big.Int).Rsh(n, 64).Uint64()
} else {
twoTo128 := new(big.Int).Lsh(big.NewInt(1), 128)
unsigned := new(big.Int).Add(n, twoTo128)
mask := new(big.Int).SetUint64(0xFFFFFFFFFFFFFFFF)
low = new(big.Int).And(unsigned, mask).Uint64()
high = new(big.Int).Rsh(unsigned, 64).Uint64()
}
value := &pb.Int128Value{Low: low, High: high}
return &pb.DecimalValue{Precision: int32(precision), Scale: scale, Value: value}
}
// relationIdKey is used as a map key for RelationIds
type relationIdKey struct {
Low uint64
High uint64
}
func computeLineStarts(text string) []int {
starts := []int{0}
for i, ch := range text {
if ch == '\n' {
starts = append(starts, i+1)
}
}
return starts
}
// Parser is an LL(k) recursive-descent parser
type Parser struct {
tokens []Token
pos int
idToDebugInfo map[string]map[relationIdKey]string
currentFragmentID []byte
Provenance map[int]Span
lineStarts []int
}
// NewParser creates a new parser
func NewParser(tokens []Token, input string) *Parser {
return &Parser{
tokens: tokens,
pos: 0,
idToDebugInfo: make(map[string]map[relationIdKey]string),
currentFragmentID: nil,
Provenance: make(map[int]Span),
lineStarts: computeLineStarts(input),
}
}
func (p *Parser) makeLocation(offset int) Location {
lo, hi := 0, len(p.lineStarts)
for lo < hi {
mid := (lo + hi) / 2
if p.lineStarts[mid] <= offset {
lo = mid + 1
} else {
hi = mid
}
}
lineIdx := lo - 1
col := offset - p.lineStarts[lineIdx]
return Location{Line: lineIdx + 1, Column: col + 1, Offset: offset}
}
func (p *Parser) spanStart() int {
return p.lookahead(0).StartPos
}
func (p *Parser) recordSpan(startOffset int, typeName string) {
// First-wins: innermost parse function records first; outer wrappers
// that share the same offset do not overwrite.
if _, exists := p.Provenance[startOffset]; exists {
return
}
endOffset := startOffset
if p.pos > 0 {
endOffset = p.tokens[p.pos-1].EndPos
}
s := Span{
Start: p.makeLocation(startOffset),
Stop: p.makeLocation(endOffset),
TypeName: typeName,
}
p.Provenance[startOffset] = s
}
func (p *Parser) lookahead(k int) Token {
idx := p.pos + k
if idx < len(p.tokens) {
return p.tokens[idx]
}
return Token{Type: "$", Value: TokenValue{}, StartPos: -1, EndPos: -1}
}
func (p *Parser) consumeLiteral(expected string) {
if !p.matchLookaheadLiteral(expected, 0) {
token := p.lookahead(0)
panic(ParseError{msg: fmt.Sprintf("Expected literal %q but got %s=`%v` at position %d", expected, token.Type, token.Value, token.StartPos)})
}
p.pos++
}
func (p *Parser) consumeTerminal(expected string) Token {
if !p.matchLookaheadTerminal(expected, 0) {
token := p.lookahead(0)
panic(ParseError{msg: fmt.Sprintf("Expected terminal %s but got %s=`%v` at position %d", expected, token.Type, token.Value, token.StartPos)})
}
token := p.lookahead(0)
p.pos++
return token
}
func (p *Parser) matchLookaheadLiteral(literal string, k int) bool {
token := p.lookahead(k)
// Support soft keywords: alphanumeric literals are lexed as SYMBOL tokens
if token.Type == "LITERAL" && token.Value.str == literal {
return true
}
if token.Type == "SYMBOL" && token.Value.str == literal {
return true
}
return false
}
func (p *Parser) matchLookaheadTerminal(terminal string, k int) bool {
token := p.lookahead(k)
return token.Type == terminal
}
func (p *Parser) startFragment(fragmentID *pb.FragmentId) *pb.FragmentId {
p.currentFragmentID = fragmentID.Id
return fragmentID
}
func (p *Parser) relationIdFromString(name string) *pb.RelationId {
hash := sha256.Sum256([]byte(name))
// Use big-endian and the lower 128 bits of the hash, consistent with pyrel.
high := binary.BigEndian.Uint64(hash[16:24])
low := binary.BigEndian.Uint64(hash[24:32])
relationId := &pb.RelationId{IdLow: low, IdHigh: high}
// Store the mapping for the current fragment if we're inside one
if p.currentFragmentID != nil {
fragKey := string(p.currentFragmentID)
if _, ok := p.idToDebugInfo[fragKey]; !ok {
p.idToDebugInfo[fragKey] = make(map[relationIdKey]string)
}
idKey := relationIdKey{Low: low, High: high}
p.idToDebugInfo[fragKey][idKey] = name
}
return relationId
}
func (p *Parser) constructFragment(fragmentID *pb.FragmentId, declarations []*pb.Declaration) *pb.Fragment {
fragKey := string(fragmentID.Id)
debugInfoMap := p.idToDebugInfo[fragKey]
var ids []*pb.RelationId
var origNames []string
for idKey, name := range debugInfoMap {
ids = append(ids, &pb.RelationId{IdLow: idKey.Low, IdHigh: idKey.High})
origNames = append(origNames, name)
}
debugInfo := &pb.DebugInfo{Ids: ids, OrigNames: origNames}
p.currentFragmentID = nil
return &pb.Fragment{Id: fragmentID, Declarations: declarations, DebugInfo: debugInfo}
}
func (p *Parser) relationIdToString(msg *pb.RelationId) string {
key := relationIdKey{Low: msg.GetIdLow(), High: msg.GetIdHigh()}
for _, debugInfoMap := range p.idToDebugInfo {
if name, ok := debugInfoMap[key]; ok {
return name
}
}
return ""
}
func (p *Parser) relationIdToUint128(msg *pb.RelationId) *pb.UInt128Value {
return &pb.UInt128Value{Low: msg.GetIdLow(), High: msg.GetIdHigh()}
}
// Helper functions
func dictFromList(pairs [][]interface{}) map[string]interface{} {
result := make(map[string]interface{})
for _, pair := range pairs {
if len(pair) >= 2 {
result[pair[0].(string)] = pair[1]
}
}
return result
}
// stringMapFromPairs builds map[string]string from (prop key value) pair rows.
func stringMapFromPairs(pairs [][]interface{}) map[string]string {
out := make(map[string]string)
for _, pair := range pairs {
if len(pair) >= 2 {
k, _ := pair[0].(string)
v, _ := pair[1].(string)
out[k] = v
}
}
return out
}
// dictGetValue retrieves a Value from the config dict with type assertion
func dictGetValue(m map[string]interface{}, key string) *pb.Value {
if v, ok := m[key]; ok {
if val, ok := v.(*pb.Value); ok {
return val
}
}
return nil
}
func listConcat[T any](a []T, b []T) []T {
if b == nil {
return a
}
result := make([]T, len(a)+len(b))
copy(result, a)
copy(result[len(a):], b)
return result
}
// hasProtoField checks if a proto message field is populated.
// Uses the proto reflection API for correct oneof detection.
func hasProtoField(msg interface{}, fieldName string) bool {
if msg == nil {
return false
}
if pm, ok := msg.(protoreflect.ProtoMessage); ok {
m := pm.ProtoReflect()
fd := m.Descriptor().Fields().ByName(protoreflect.Name(fieldName))
if fd != nil {
return m.Has(fd)
}
}
// Fallback: getter-based reflection for non-proto types.
val := reflect.ValueOf(msg)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return false
}
methodName := "Get" + toPascalCase(fieldName)
method := reflect.ValueOf(msg).MethodByName(methodName)
if !method.IsValid() {
return false
}
results := method.Call(nil)
if len(results) == 0 {
return false
}
result := results[0]
if result.Kind() == reflect.Ptr || result.Kind() == reflect.Interface {
return !result.IsNil()
}
return true
}
func toPascalCase(s string) string {
parts := strings.Split(s, "_")
for i, part := range parts {
if len(part) > 0 {
parts[i] = strings.ToUpper(part[:1]) + part[1:]
}
}
return strings.Join(parts, "")
}
// --- Helper functions ---
func (p *Parser) _extract_value_int32(value *pb.Value, default_ int64) int32 {
var _t2116 interface{}
if (value != nil && hasProtoField(value, "int32_value")) {
return value.GetInt32Value()
}
_ = _t2116
return int32(default_)
}
func (p *Parser) _extract_value_int64(value *pb.Value, default_ int64) int64 {
var _t2117 interface{}
if (value != nil && hasProtoField(value, "int_value")) {
return value.GetIntValue()
}
_ = _t2117
return default_
}
func (p *Parser) _extract_value_string(value *pb.Value, default_ string) string {
var _t2118 interface{}
if (value != nil && hasProtoField(value, "string_value")) {
return value.GetStringValue()
}
_ = _t2118
return default_
}
func (p *Parser) _extract_value_boolean(value *pb.Value, default_ bool) bool {
var _t2119 interface{}
if (value != nil && hasProtoField(value, "boolean_value")) {
return value.GetBooleanValue()
}
_ = _t2119
return default_
}
func (p *Parser) _extract_value_string_list(value *pb.Value, default_ []string) []string {
var _t2120 interface{}
if (value != nil && hasProtoField(value, "string_value")) {
return []string{value.GetStringValue()}
}
_ = _t2120
return default_
}
func (p *Parser) _try_extract_value_int64(value *pb.Value) *int64 {
var _t2121 interface{}
if (value != nil && hasProtoField(value, "int_value")) {
return ptr(value.GetIntValue())
}
_ = _t2121
return nil
}
func (p *Parser) _try_extract_value_float64(value *pb.Value) *float64 {
var _t2122 interface{}
if (value != nil && hasProtoField(value, "float_value")) {
return ptr(value.GetFloatValue())
}
_ = _t2122
return nil
}
func (p *Parser) _try_extract_value_bytes(value *pb.Value) []byte {
var _t2123 interface{}
if (value != nil && hasProtoField(value, "string_value")) {
return []byte(value.GetStringValue())
}
_ = _t2123
return nil
}
func (p *Parser) _try_extract_value_uint128(value *pb.Value) *pb.UInt128Value {
var _t2124 interface{}
if (value != nil && hasProtoField(value, "uint128_value")) {
return value.GetUint128Value()
}
_ = _t2124
return nil
}
func (p *Parser) construct_csv_config(config_dict [][]interface{}) *pb.CSVConfig {
config := dictFromList(config_dict)
_t2125 := p._extract_value_int32(dictGetValue(config, "csv_header_row"), 1)
header_row := _t2125
_t2126 := p._extract_value_int64(dictGetValue(config, "csv_skip"), 0)
skip := _t2126
_t2127 := p._extract_value_string(dictGetValue(config, "csv_new_line"), "")
new_line := _t2127
_t2128 := p._extract_value_string(dictGetValue(config, "csv_delimiter"), ",")
delimiter := _t2128
_t2129 := p._extract_value_string(dictGetValue(config, "csv_quotechar"), "\"")
quotechar := _t2129
_t2130 := p._extract_value_string(dictGetValue(config, "csv_escapechar"), "\"")
escapechar := _t2130
_t2131 := p._extract_value_string(dictGetValue(config, "csv_comment"), "")
comment := _t2131
_t2132 := p._extract_value_string_list(dictGetValue(config, "csv_missing_strings"), []string{})
missing_strings := _t2132
_t2133 := p._extract_value_string(dictGetValue(config, "csv_decimal_separator"), ".")
decimal_separator := _t2133
_t2134 := p._extract_value_string(dictGetValue(config, "csv_encoding"), "utf-8")
encoding := _t2134
_t2135 := p._extract_value_string(dictGetValue(config, "csv_compression"), "auto")
compression := _t2135
_t2136 := p._extract_value_int64(dictGetValue(config, "csv_partition_size_mb"), 0)
partition_size_mb := _t2136
_t2137 := &pb.CSVConfig{HeaderRow: header_row, Skip: skip, NewLine: new_line, Delimiter: delimiter, Quotechar: quotechar, Escapechar: escapechar, Comment: comment, MissingStrings: missing_strings, DecimalSeparator: decimal_separator, Encoding: encoding, Compression: compression, PartitionSizeMb: partition_size_mb}
return _t2137
}
func (p *Parser) construct_betree_info(key_types []*pb.Type, value_types []*pb.Type, config_dict [][]interface{}) *pb.BeTreeInfo {
config := dictFromList(config_dict)
_t2138 := p._try_extract_value_float64(dictGetValue(config, "betree_config_epsilon"))
epsilon := _t2138
_t2139 := p._try_extract_value_int64(dictGetValue(config, "betree_config_max_pivots"))
max_pivots := _t2139
_t2140 := p._try_extract_value_int64(dictGetValue(config, "betree_config_max_deltas"))
max_deltas := _t2140
_t2141 := p._try_extract_value_int64(dictGetValue(config, "betree_config_max_leaf"))
max_leaf := _t2141
_t2142 := &pb.BeTreeConfig{Epsilon: deref(epsilon, 0.0), MaxPivots: deref(max_pivots, 0), MaxDeltas: deref(max_deltas, 0), MaxLeaf: deref(max_leaf, 0)}
storage_config := _t2142
_t2143 := p._try_extract_value_uint128(dictGetValue(config, "betree_locator_root_pageid"))
root_pageid := _t2143
_t2144 := p._try_extract_value_bytes(dictGetValue(config, "betree_locator_inline_data"))
inline_data := _t2144
_t2145 := p._try_extract_value_int64(dictGetValue(config, "betree_locator_element_count"))
element_count := _t2145
_t2146 := p._try_extract_value_int64(dictGetValue(config, "betree_locator_tree_height"))
tree_height := _t2146
_t2147 := &pb.BeTreeLocator{ElementCount: deref(element_count, 0), TreeHeight: deref(tree_height, 0)}
if root_pageid != nil {
_t2147.Location = &pb.BeTreeLocator_RootPageid{RootPageid: root_pageid}
} else {
_t2147.Location = &pb.BeTreeLocator_InlineData{InlineData: inline_data}
}
relation_locator := _t2147
_t2148 := &pb.BeTreeInfo{KeyTypes: key_types, ValueTypes: value_types, StorageConfig: storage_config, RelationLocator: relation_locator}
return _t2148
}
func (p *Parser) default_configure() *pb.Configure {
_t2149 := &pb.IVMConfig{Level: pb.MaintenanceLevel_MAINTENANCE_LEVEL_OFF}
ivm_config := _t2149
_t2150 := &pb.Configure{SemanticsVersion: 0, IvmConfig: ivm_config}
return _t2150
}
func (p *Parser) construct_configure(config_dict [][]interface{}) *pb.Configure {
config := dictFromList(config_dict)
maintenance_level_val := dictGetValue(config, "ivm.maintenance_level")
maintenance_level := pb.MaintenanceLevel_MAINTENANCE_LEVEL_OFF
if (maintenance_level_val != nil && hasProtoField(maintenance_level_val, "string_value")) {
if maintenance_level_val.GetStringValue() == "off" {
maintenance_level = pb.MaintenanceLevel_MAINTENANCE_LEVEL_OFF
} else {
if maintenance_level_val.GetStringValue() == "auto" {
maintenance_level = pb.MaintenanceLevel_MAINTENANCE_LEVEL_AUTO
} else {
if maintenance_level_val.GetStringValue() == "all" {
maintenance_level = pb.MaintenanceLevel_MAINTENANCE_LEVEL_ALL
} else {
maintenance_level = pb.MaintenanceLevel_MAINTENANCE_LEVEL_OFF
}
}
}
}
_t2151 := &pb.IVMConfig{Level: maintenance_level}
ivm_config := _t2151
_t2152 := p._extract_value_int64(dictGetValue(config, "semantics_version"), 0)
semantics_version := _t2152
_t2153 := &pb.Configure{SemanticsVersion: semantics_version, IvmConfig: ivm_config}
return _t2153
}
func (p *Parser) construct_export_csv_config(path string, columns []*pb.ExportCSVColumn, config_dict [][]interface{}) *pb.ExportCSVConfig {
config := dictFromList(config_dict)
_t2154 := p._extract_value_int64(dictGetValue(config, "partition_size"), 0)
partition_size := _t2154
_t2155 := p._extract_value_string(dictGetValue(config, "compression"), "")
compression := _t2155
_t2156 := p._extract_value_boolean(dictGetValue(config, "syntax_header_row"), true)
syntax_header_row := _t2156
_t2157 := p._extract_value_string(dictGetValue(config, "syntax_missing_string"), "")
syntax_missing_string := _t2157
_t2158 := p._extract_value_string(dictGetValue(config, "syntax_delim"), ",")
syntax_delim := _t2158
_t2159 := p._extract_value_string(dictGetValue(config, "syntax_quotechar"), "\"")
syntax_quotechar := _t2159
_t2160 := p._extract_value_string(dictGetValue(config, "syntax_escapechar"), "\\")
syntax_escapechar := _t2160
_t2161 := &pb.ExportCSVConfig{Path: path, DataColumns: columns, PartitionSize: ptr(partition_size), Compression: ptr(compression), SyntaxHeaderRow: ptr(syntax_header_row), SyntaxMissingString: ptr(syntax_missing_string), SyntaxDelim: ptr(syntax_delim), SyntaxQuotechar: ptr(syntax_quotechar), SyntaxEscapechar: ptr(syntax_escapechar)}
return _t2161
}
func (p *Parser) construct_export_csv_config_with_source(path string, csv_source *pb.ExportCSVSource, csv_config *pb.CSVConfig) *pb.ExportCSVConfig {
_t2162 := &pb.ExportCSVConfig{Path: path, CsvSource: csv_source, CsvConfig: csv_config}
return _t2162
}
func (p *Parser) construct_iceberg_catalog_config(catalog_uri string, scope_opt *string, property_pairs [][]interface{}, auth_property_pairs [][]interface{}) *pb.IcebergCatalogConfig {
props := stringMapFromPairs(property_pairs)
auth_props := stringMapFromPairs(auth_property_pairs)
_t2163 := &pb.IcebergCatalogConfig{CatalogUri: catalog_uri, Scope: ptr(deref(scope_opt, "")), Properties: props, AuthProperties: auth_props}
return _t2163
}
func (p *Parser) construct_iceberg_data(locator *pb.IcebergLocator, config *pb.IcebergCatalogConfig, columns []*pb.GNFColumn, from_snapshot_opt *string, to_snapshot_opt *string, returns_delta bool) *pb.IcebergData {
_t2164 := &pb.IcebergData{Locator: locator, Config: config, Columns: columns, FromSnapshot: ptr(deref(from_snapshot_opt, "")), ToSnapshot: ptr(deref(to_snapshot_opt, "")), ReturnsDelta: returns_delta}
return _t2164
}
func (p *Parser) construct_export_iceberg_config_full(locator *pb.IcebergLocator, config *pb.IcebergCatalogConfig, table_def *pb.RelationId, columns []*pb.ExportColumn, table_property_pairs [][]interface{}, config_dict [][]interface{}) *pb.ExportIcebergConfig {
_t2165 := config_dict
if config_dict == nil {
_t2165 = [][]interface{}{}
}
cfg := dictFromList(_t2165)
_t2166 := p._extract_value_string(dictGetValue(cfg, "prefix"), "")
prefix := _t2166
_t2167 := p._extract_value_int64(dictGetValue(cfg, "target_file_size_bytes"), 0)
target_file_size_bytes := _t2167
_t2168 := p._extract_value_string(dictGetValue(cfg, "compression"), "")
compression := _t2168
table_props := stringMapFromPairs(table_property_pairs)
_t2169 := &pb.ExportIcebergConfig{Locator: locator, Config: config, TableDef: table_def, Columns: columns, Prefix: ptr(prefix), TargetFileSizeBytes: ptr(target_file_size_bytes), Compression: compression, TableProperties: table_props}
return _t2169
}
// --- Parse functions ---
func (p *Parser) parse_transaction() *pb.Transaction {
span_start680 := int64(p.spanStart())
p.consumeLiteral("(")
p.consumeLiteral("transaction")
var _t1348 *pb.Configure
if (p.matchLookaheadLiteral("(", 0) && p.matchLookaheadLiteral("configure", 1)) {
_t1349 := p.parse_configure()
_t1348 = _t1349
}
configure674 := _t1348
var _t1350 *pb.Sync
if (p.matchLookaheadLiteral("(", 0) && p.matchLookaheadLiteral("sync", 1)) {
_t1351 := p.parse_sync()
_t1350 = _t1351
}
sync675 := _t1350
xs676 := []*pb.Epoch{}
cond677 := p.matchLookaheadLiteral("(", 0)
for cond677 {
_t1352 := p.parse_epoch()
item678 := _t1352
xs676 = append(xs676, item678)
cond677 = p.matchLookaheadLiteral("(", 0)
}
epochs679 := xs676
p.consumeLiteral(")")
_t1353 := p.default_configure()
_t1354 := configure674
if configure674 == nil {
_t1354 = _t1353
}
_t1355 := &pb.Transaction{Epochs: epochs679, Configure: _t1354, Sync: sync675}
result681 := _t1355
p.recordSpan(int(span_start680), "Transaction")
return result681
}
func (p *Parser) parse_configure() *pb.Configure {
span_start683 := int64(p.spanStart())
p.consumeLiteral("(")
p.consumeLiteral("configure")
_t1356 := p.parse_config_dict()
config_dict682 := _t1356
p.consumeLiteral(")")
_t1357 := p.construct_configure(config_dict682)
result684 := _t1357
p.recordSpan(int(span_start683), "Configure")
return result684
}
func (p *Parser) parse_config_dict() [][]interface{} {
p.consumeLiteral("{")
xs685 := [][]interface{}{}
cond686 := p.matchLookaheadLiteral(":", 0)
for cond686 {
_t1358 := p.parse_config_key_value()
item687 := _t1358
xs685 = append(xs685, item687)
cond686 = p.matchLookaheadLiteral(":", 0)
}
config_key_values688 := xs685
p.consumeLiteral("}")
return config_key_values688
}
func (p *Parser) parse_config_key_value() []interface{} {
p.consumeLiteral(":")
symbol689 := p.consumeTerminal("SYMBOL").Value.str
_t1359 := p.parse_raw_value()
raw_value690 := _t1359
return []interface{}{symbol689, raw_value690}
}
func (p *Parser) parse_raw_value() *pb.Value {
span_start704 := int64(p.spanStart())
var _t1360 int64
if p.matchLookaheadLiteral("true", 0) {
_t1360 = 12
} else {
var _t1361 int64
if p.matchLookaheadLiteral("missing", 0) {
_t1361 = 11
} else {
var _t1362 int64
if p.matchLookaheadLiteral("false", 0) {
_t1362 = 12
} else {
var _t1363 int64
if p.matchLookaheadLiteral("(", 0) {
var _t1364 int64
if p.matchLookaheadLiteral("datetime", 1) {
_t1364 = 1
} else {
var _t1365 int64
if p.matchLookaheadLiteral("date", 1) {
_t1365 = 0
} else {
_t1365 = -1
}
_t1364 = _t1365
}
_t1363 = _t1364
} else {
var _t1366 int64
if p.matchLookaheadTerminal("UINT32", 0) {
_t1366 = 7
} else {
var _t1367 int64
if p.matchLookaheadTerminal("UINT128", 0) {
_t1367 = 8
} else {
var _t1368 int64