Repository navigation
Expand file tree
/
Copy pathdecoder.go
More file actions
1116 lines (1026 loc) · 27.9 KB
/
Copy pathdecoder.go
File metadata and controls
1116 lines (1026 loc) · 27.9 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
package toon
import (
"errors"
"fmt"
"math"
"slices"
"strconv"
"strings"
"unicode/utf8"
formatpkg "github.com/toon-format/toon-go/internal/format"
parsepkg "github.com/toon-format/toon-go/internal/parse"
)
// Decoder parses TOON documents into float64 numbers, map[string]any objects,
// and []any arrays. Go maps keep no insertion order, so document key order is
// lost. The zero value decodes with the default options. A Decoder is safe for
// concurrent use.
type Decoder struct {
opts []DecoderOption
}
// NewDecoder constructs a Decoder with the given options.
func NewDecoder(opts ...DecoderOption) *Decoder {
return &Decoder{opts: slices.Clone(opts)}
}
// Decode parses the provided TOON document. The bytes must be UTF-8;
// ill-formed sequences are an error in any mode.
func (d *Decoder) Decode(data []byte) (any, error) {
return d.DecodeString(string(data))
}
// invalidUTF8Error reports the line of the first ill-formed UTF-8 sequence.
func invalidUTF8Error(doc string) error {
offset := 0
for offset < len(doc) {
r, size := utf8.DecodeRuneInString(doc[offset:])
if r == utf8.RuneError && size <= 1 {
break
}
offset += size
}
line := strings.Count(doc[:offset], "\n") + 1
return errorAt(line, "invalid UTF-8 sequence")
}
// DecodeString parses the provided TOON document. The document must be
// UTF-8; ill-formed sequences are an error in any mode.
func (d *Decoder) DecodeString(doc string) (any, error) {
if !utf8.ValidString(doc) {
return nil, invalidUTF8Error(doc)
}
cfg := defaultDecoderOptions()
for _, opt := range d.opts {
opt(&cfg)
}
lines, err := prepareLines(doc, cfg)
if err != nil {
return nil, err
}
p := newParser(lines, cfg)
return p.parseDocument()
}
// Decode parses the TOON document in data.
func Decode(data []byte, opts ...DecoderOption) (any, error) {
return NewDecoder(opts...).Decode(data)
}
// DecodeString parses the TOON document s.
func DecodeString(s string, opts ...DecoderOption) (any, error) {
return NewDecoder(opts...).DecodeString(s)
}
// docLine is one line of the comment-stripped document.
type docLine struct {
number int
depth int
content string
blank bool
}
// prepareLines removes the byte-order mark, normalizes line terminators, strips
// comment lines and trailing spaces, and computes each line's depth.
func prepareLines(input string, cfg decoderOptions) ([]docLine, error) {
input = strings.TrimPrefix(input, "\ufeff")
raw := strings.Split(input, "\n")
lines := make([]docLine, 0, len(raw))
for i, text := range raw {
number := i + 1
text = strings.TrimSuffix(text, "\r")
text = strings.TrimRight(text, " ")
if isCommentLine(text) {
continue
}
if text == "" {
lines = append(lines, docLine{number: number, blank: true})
continue
}
depth, content, err := lineDepth(text, cfg)
if err != nil {
return nil, errorWrap(number, err)
}
if content == "" {
// Only the non-strict tab leniency leaves a line of nothing but
// indentation, and that leniency counts it as blank.
lines = append(lines, docLine{number: number, blank: true})
continue
}
lines = append(lines, docLine{number: number, depth: depth, content: content})
}
// A final newline produces a trailing empty line that carries no meaning.
if n := len(lines); n > 0 && lines[n-1].blank {
lines = lines[:n-1]
}
return lines, nil
}
// isCommentLine reports whether the line's first character after zero or more
// spaces is "#". A tab in the leading whitespace disqualifies it.
func isCommentLine(text string) bool {
i := 0
for i < len(text) && text[i] == ' ' {
i++
}
return i < len(text) && text[i] == '#'
}
func lineDepth(text string, cfg decoderOptions) (int, string, error) {
spaces, tabs, offset := 0, 0, 0
scan:
for offset < len(text) {
switch text[offset] {
case ' ':
spaces++
case '\t':
tabs++
default:
break scan
}
offset++
}
if cfg.strict {
if tabs > 0 {
return 0, "", errors.New("tabs are not allowed in indentation")
}
if spaces%cfg.indentSize != 0 {
return 0, "", fmt.Errorf("indentation must be a multiple of %d spaces", cfg.indentSize)
}
return spaces / cfg.indentSize, text[offset:], nil
}
return spaces/cfg.indentSize + tabs, text[offset:], nil
}
type parser struct {
lines []docLine
pos int
cfg decoderOptions
spans []*spanState
// nonBlank[i] is the index of the first non-blank line at or after i, or
// len(lines) if there is none. It keeps blank-line lookahead O(1).
nonBlank []int
}
func newParser(lines []docLine, cfg decoderOptions) *parser {
nonBlank := make([]int, len(lines)+1)
nonBlank[len(lines)] = len(lines)
for i := len(lines) - 1; i >= 0; i-- {
if lines[i].blank {
nonBlank[i] = nonBlank[i+1]
} else {
nonBlank[i] = i
}
}
return &parser{lines: lines, cfg: cfg, nonBlank: nonBlank}
}
// spanState tracks an open header span: the scope's content depth and how many
// items, rows, or entry rows it has consumed so far.
type spanState struct {
contentDepth int
consumed int
}
func (p *parser) pushSpan(contentDepth int) *spanState {
span := &spanState{contentDepth: contentDepth}
p.spans = append(p.spans, span)
return span
}
func (p *parser) popSpan() {
p.spans = p.spans[:len(p.spans)-1]
}
// checkBlank rejects a blank line that falls inside an open header span. The
// span reaches through the last line of the scope's content, which may sit
// deeper than the scope itself, so every open span is consulted.
func (p *parser) checkBlank() error {
if !p.cfg.strict {
return nil
}
idx, ok := p.nextNonBlank(p.pos + 1)
if !ok {
return nil
}
next := p.lines[idx]
for _, span := range p.spans {
if span.consumed > 0 && next.depth >= span.contentDepth {
return errorAt(p.lines[p.pos].number, "blank line inside a header span")
}
}
return nil
}
// scopeEndsAtBlank reports whether the scope at contentDepth ends at the blank
// line under the cursor.
func (p *parser) scopeEndsAtBlank(contentDepth int) bool {
idx, ok := p.nextNonBlank(p.pos + 1)
return !ok || p.lines[idx].depth < contentDepth
}
func (p *parser) nextNonBlank(from int) (int, bool) {
if from >= len(p.lines) {
return 0, false
}
idx := p.nonBlank[from]
return idx, idx < len(p.lines)
}
func (p *parser) countNonBlank() int {
count := 0
for _, line := range p.lines {
if !line.blank {
count++
}
}
return count
}
func (p *parser) parseDocument() (any, error) {
idx, ok := p.nextNonBlank(0)
if !ok {
return map[string]any{}, nil
}
p.pos = idx
line := p.lines[idx]
if line.depth > 0 {
return nil, errorAt(line.number, "unexpected indentation")
}
if line.content == "[]" {
p.pos++
if err := p.checkTrailing(); err != nil {
return nil, err
}
return []any{}, nil
}
hdr, status := parseHeaderSyntax(line.content, p.cfg.strict)
hdr.number = line.number
switch status {
case headerOK:
if !hdr.hasKey {
p.pos++
var value any
var err error
if hdr.keyed {
value, err = p.parseKeyedRows(hdr, line.depth+1)
} else {
value, err = p.parseArrayBody(hdr, line.depth+1)
}
if err != nil {
return nil, err
}
if err := p.checkTrailing(); err != nil {
return nil, err
}
return value, nil
}
case headerMalformed:
return nil, hdr.malformedError()
}
if p.countNonBlank() == 1 && isScalarLine(line.content) {
p.pos++
value, err := decodeValueToken(line.content)
if err != nil {
return nil, errorWrap(line.number, err)
}
return value, nil
}
result := map[string]any{}
seen := map[string]bool{}
if err := p.parseObjectInto(result, seen, 0, 0); err != nil {
return nil, err
}
return result, nil
}
func (p *parser) checkTrailing() error {
if idx, ok := p.nextNonBlank(p.pos); ok {
return errorAt(p.lines[idx].number, "trailing content after the root form")
}
return nil
}
// parseObjectInto fills result with the fields of an object scope whose content
// stands at depth. The scope ends at the first line shallower than minDepth,
// which lies below depth only for an adopted depth.
func (p *parser) parseObjectInto(result map[string]any, seen map[string]bool, minDepth, depth int) error {
for p.pos < len(p.lines) {
line := p.lines[p.pos]
if line.blank {
if err := p.checkBlank(); err != nil {
return err
}
p.pos++
continue
}
if line.depth < minDepth {
return nil
}
if line.depth != depth {
return errorAt(line.number, "unexpected indentation")
}
hdr, status := parseHeaderSyntax(line.content, p.cfg.strict)
hdr.number = line.number
if status == headerOK && hdr.hasKey {
p.pos++
var value any
var err error
if hdr.keyed {
value, err = p.parseKeyedRows(hdr, depth+1)
} else {
value, err = p.parseArrayBody(hdr, depth+1)
}
if err != nil {
return err
}
if err := p.assign(result, seen, hdr.key, value, line.number); err != nil {
return err
}
continue
}
switch {
case status == headerOK && !hdr.hasKey:
return errorAt(line.number, "keyless array header inside an object")
case status == headerMalformed:
return hdr.malformedError()
}
key, value, err := p.parseKeyValueLine(line, depth)
if err != nil {
return err
}
if err := p.assign(result, seen, key, value, line.number); err != nil {
return err
}
}
return nil
}
// scopeDepth returns the content depth of the scope whose first line is the next
// non-blank one, given the depth its content belongs at. Non-strict mode takes
// a jumped first line's depth, so the scope reads the lines that follow at that
// depth rather than rejecting them all as over-indented.
func (p *parser) scopeDepth(depth int) int {
if idx, ok := p.nextNonBlank(p.pos); ok && !p.cfg.strict && p.lines[idx].depth > depth {
return p.lines[idx].depth
}
return depth
}
// parseKeyValueLine consumes a key-value line whose key stands at depth and
// returns its decoded key and value.
func (p *parser) parseKeyValueLine(line docLine, depth int) (string, any, error) {
colon := parsepkg.IndexUnquoted(line.content, ':')
if colon < 0 {
// A scalar line outside root primitive position is an error in any mode.
return "", nil, errorAt(line.number, "expected a key-value line")
}
key, err := decodeKeyToken(strings.Trim(line.content[:colon], " "))
if err != nil {
return "", nil, errorWrap(line.number, err)
}
rest := strings.Trim(line.content[colon+1:], " ")
p.pos++
switch rest {
case "":
nested, err := p.parseNestedObject(depth + 1)
if err != nil {
return "", nil, err
}
return key, nested, nil
case "[]":
return key, []any{}, nil
}
value, err := decodeValueToken(rest)
if err != nil {
return "", nil, errorWrap(line.number, err)
}
return key, value, nil
}
func (p *parser) parseNestedObject(depth int) (map[string]any, error) {
result := map[string]any{}
idx, ok := p.nextNonBlank(p.pos)
if !ok || p.lines[idx].depth < depth {
return result, nil
}
if p.lines[idx].depth > depth && p.cfg.strict {
return nil, errorAt(p.lines[idx].number, "indentation depth jump")
}
seen := map[string]bool{}
if err := p.parseObjectInto(result, seen, depth, p.scopeDepth(depth)); err != nil {
return nil, err
}
return result, nil
}
func (p *parser) assign(result map[string]any, seen map[string]bool, key string, value any, number int) error {
if seen[key] {
if p.cfg.strict {
return errorAtf(number, "duplicate sibling key %q", key)
}
}
seen[key] = true
result[key] = value
return nil
}
// parseArrayBody decodes the value of a non-keyed header whose scope content
// stands at contentDepth.
func (p *parser) parseArrayBody(hdr header, contentDepth int) (any, error) {
if hdr.fields != nil {
return p.parseTabularRows(hdr, contentDepth)
}
if hdr.inline != "" {
return p.parseInlineValues(hdr)
}
return p.parseListItems(hdr, contentDepth)
}
func (p *parser) parseInlineValues(hdr header) (any, error) {
tokens := parsepkg.SplitDelimited(hdr.inline, hdr.delimiter.rune())
values := make([]any, 0, len(tokens))
for _, token := range tokens {
value, err := decodeValueToken(token)
if err != nil {
return nil, errorWrap(hdr.number, err)
}
values = append(values, value)
}
if p.cfg.strict && len(values) != hdr.length {
return nil, errorAtf(hdr.number, "inline array declares %d values but carries %d", hdr.length, len(values))
}
return values, nil
}
func (p *parser) parseTabularRows(hdr header, contentDepth int) (any, error) {
leaves := leafCount(hdr.fields)
rows := []any{}
delimiter := hdr.delimiter.rune()
rowDepth := p.scopeDepth(contentDepth)
span := p.pushSpan(contentDepth)
defer p.popSpan()
for p.pos < len(p.lines) {
line := p.lines[p.pos]
if line.blank {
if err := p.checkBlank(); err != nil {
return nil, err
}
ends := p.scopeEndsAtBlank(contentDepth)
p.pos++
if ends {
break
}
continue
}
if line.depth < contentDepth {
break
}
if line.depth != rowDepth {
return nil, errorAt(line.number, "unexpected indentation in tabular scope")
}
if !isRowLine(line.content, delimiter) {
break
}
p.pos++
cells := parsepkg.SplitDelimited(line.content, delimiter)
if len(cells) != leaves {
return nil, errorAtf(line.number, "tabular row carries %d cells but the header declares %d", len(cells), leaves)
}
index := 0
row, err := buildFromCells(hdr.fields, cells, &index)
if err != nil {
return nil, errorWrap(line.number, err)
}
rows = append(rows, row)
span.consumed++
}
if p.cfg.strict && len(rows) != hdr.length {
return nil, errorAtf(hdr.number, "tabular array declares %d rows but carries %d", hdr.length, len(rows))
}
return rows, nil
}
// isRowLine reports whether content is a tabular row rather than the key-value
// line that ends the rows.
func isRowLine(content string, delimiter rune) bool {
colon := parsepkg.IndexUnquoted(content, ':')
if colon < 0 {
return true
}
delim := parsepkg.IndexUnquoted(content, delimiter)
return delim >= 0 && delim < colon
}
func (p *parser) parseKeyedRows(hdr header, contentDepth int) (any, error) {
leaves := leafCount(hdr.fields)
result := map[string]any{}
seen := map[string]bool{}
delimiter := hdr.delimiter.rune()
count := 0
entryDepth := p.scopeDepth(contentDepth)
span := p.pushSpan(contentDepth)
defer p.popSpan()
for p.pos < len(p.lines) {
line := p.lines[p.pos]
if line.blank {
if err := p.checkBlank(); err != nil {
return nil, err
}
ends := p.scopeEndsAtBlank(contentDepth)
p.pos++
if ends {
break
}
continue
}
if line.depth < contentDepth {
break
}
if line.depth != entryDepth {
return nil, errorAt(line.number, "unexpected indentation in keyed tabular scope")
}
colon := parsepkg.IndexUnquoted(line.content, ':')
if colon < 0 {
return nil, errorAt(line.number, "entry row is missing a colon")
}
p.pos++
key, err := decodeKeyToken(strings.Trim(line.content[:colon], " "))
if err != nil {
return nil, errorWrap(line.number, err)
}
cells := parsepkg.SplitDelimited(strings.Trim(line.content[colon+1:], " "), delimiter)
if len(cells) != leaves {
return nil, errorAtf(line.number, "entry row carries %d cells but the header declares %d", len(cells), leaves)
}
index := 0
value, err := buildFromCells(hdr.fields, cells, &index)
if err != nil {
return nil, errorWrap(line.number, err)
}
if err := p.assign(result, seen, key, value, line.number); err != nil {
return nil, err
}
count++
span.consumed++
}
if p.cfg.strict && count != hdr.length {
return nil, errorAtf(hdr.number, "keyed tabular object declares %d entries but carries %d", hdr.length, count)
}
return result, nil
}
func (p *parser) parseListItems(hdr header, contentDepth int) (any, error) {
items := []any{}
itemDepth := p.scopeDepth(contentDepth)
span := p.pushSpan(contentDepth)
defer p.popSpan()
for p.pos < len(p.lines) {
line := p.lines[p.pos]
if line.blank {
if err := p.checkBlank(); err != nil {
return nil, err
}
ends := p.scopeEndsAtBlank(contentDepth)
p.pos++
if ends {
break
}
continue
}
if line.depth < contentDepth {
break
}
if line.depth != itemDepth {
return nil, errorAt(line.number, "unexpected indentation in list scope")
}
if line.content != "-" && !strings.HasPrefix(line.content, "- ") {
break
}
p.pos++
span.consumed++
item, err := p.parseListItem(line, itemDepth)
if err != nil {
return nil, err
}
items = append(items, item)
}
if p.cfg.strict && len(items) != hdr.length {
return nil, errorAtf(hdr.number, "array declares %d items but carries %d", hdr.length, len(items))
}
return items, nil
}
// parseListItem decodes one list item whose hyphen stands at itemDepth. A keyed
// first field carried on the hyphen line stands at itemDepth+1, so any scope it
// opens has its content at itemDepth+2.
func (p *parser) parseListItem(line docLine, itemDepth int) (any, error) {
rest := strings.TrimLeft(strings.TrimPrefix(line.content, "-"), " ")
switch rest {
case "":
return map[string]any{}, nil
case "[]":
return []any{}, nil
}
hdr, status := parseHeaderSyntax(rest, p.cfg.strict)
hdr.number = line.number
switch status {
case headerMalformed:
return nil, hdr.malformedError()
case headerOK:
if !hdr.hasKey {
if hdr.fields != nil || hdr.keyed {
return nil, errorAt(line.number, "a keyless fields-bearing header is valid only at the document root")
}
return p.parseArrayBody(hdr, itemDepth+1)
}
result := map[string]any{}
seen := map[string]bool{}
var value any
var err error
if hdr.keyed {
value, err = p.parseKeyedRows(hdr, itemDepth+2)
} else {
value, err = p.parseArrayBody(hdr, itemDepth+2)
}
if err != nil {
return nil, err
}
if err := p.assign(result, seen, hdr.key, value, line.number); err != nil {
return nil, err
}
if err := p.parseObjectInto(result, seen, itemDepth+1, itemDepth+1); err != nil {
return nil, err
}
return result, nil
}
colon := parsepkg.IndexUnquoted(rest, ':')
if colon < 0 {
value, err := decodeValueToken(rest)
if err != nil {
return nil, errorWrap(line.number, err)
}
return value, nil
}
key, err := decodeKeyToken(strings.Trim(rest[:colon], " "))
if err != nil {
return nil, errorWrap(line.number, err)
}
valueToken := strings.Trim(rest[colon+1:], " ")
var value any
switch valueToken {
case "":
nested, nErr := p.parseNestedObject(itemDepth + 2)
if nErr != nil {
return nil, nErr
}
value = nested
case "[]":
value = []any{}
default:
value, err = decodeValueToken(valueToken)
if err != nil {
return nil, errorWrap(line.number, err)
}
}
result := map[string]any{}
seen := map[string]bool{}
if err := p.assign(result, seen, key, value, line.number); err != nil {
return nil, err
}
if err := p.parseObjectInto(result, seen, itemDepth+1, itemDepth+1); err != nil {
return nil, err
}
return result, nil
}
// isScalarLine reports whether content is a scalar line: one without an
// unquoted colon, which every header and key-value line has. Callers pass only
// lines off item depth, where a leading hyphen marks no list item.
func isScalarLine(content string) bool {
return parsepkg.IndexUnquoted(content, ':') < 0
}
// buildFromCells materializes one row or entry value by walking the field list
// depth-first.
func buildFromCells(nodes []fieldNode, cells []string, index *int) (map[string]any, error) {
result := make(map[string]any, len(nodes))
for _, node := range nodes {
if node.children != nil {
sub, err := buildFromCells(node.children, cells, index)
if err != nil {
return nil, err
}
result[node.name] = sub
continue
}
value, err := decodeValueToken(cells[*index])
if err != nil {
return nil, err
}
result[node.name] = value
*index++
}
return result, nil
}
func leafCount(nodes []fieldNode) int {
total := 0
for _, node := range nodes {
if node.children == nil {
total++
continue
}
total += leafCount(node.children)
}
return total
}
func decodeKeyToken(token string) (string, error) {
if parsepkg.IsQuotedToken(token) {
if err := parsepkg.ValidateQuotedToken(token); err != nil {
return "", err
}
return parsepkg.UnquoteString(token)
}
return token, nil
}
// decodeValueToken maps a primitive token to a host value. The empty array form
// is positional and is therefore handled by the caller.
func decodeValueToken(token string) (any, error) {
if token == "" {
return "", nil
}
if parsepkg.IsQuotedToken(token) {
if err := parsepkg.ValidateQuotedToken(token); err != nil {
return nil, err
}
return parsepkg.UnquoteString(token)
}
switch token {
case "true":
return true, nil
case "false":
return false, nil
case "null":
return nil, nil
}
if number, ok := formatpkg.ParseNumberToken(token); ok {
return number, nil
}
return token, nil
}
// header is a parsed array, tabular, or keyed header.
type header struct {
key string
hasKey bool
length int
keyed bool
delimiter Delimiter
fields []fieldNode
inline string
number int
// err tells why a malformed header's field list breaks the grammar.
err error
}
// malformedError reports a malformed header, through its field list's error
// when that list is the cause.
func (h header) malformedError() error {
if h.err != nil {
return errorWrap(h.number, h.err)
}
return errorAt(h.number, "malformed array header")
}
type headerStatus int
const (
// headerNotHeader means the line is not a header and falls through to the
// key-value class.
headerNotHeader headerStatus = iota
// headerMalformed means the line opens like a header but breaks its grammar.
headerMalformed
headerOK
)
func parseHeaderSyntax(content string, strict bool) (header, headerStatus) {
bracket := parsepkg.IndexUnquoted(content, '[')
if bracket < 0 {
return header{}, headerNotHeader
}
// A header needs a colon, and its key can't contain one. Past this check,
// a grammar failure makes the line malformed instead of a key-value line.
if colon := parsepkg.IndexUnquoted(content, ':'); colon < 0 || colon < bracket {
return header{}, headerNotHeader
}
segment, after, found := strings.Cut(content[bracket+1:], "]")
if !found {
return header{}, headerMalformed
}
hdr := header{delimiter: DelimiterComma}
keyPart := content[:bracket]
if strings.TrimRight(keyPart, " \t") != keyPart {
return header{}, headerMalformed
}
if keyPart != "" {
key, err := decodeKeyToken(keyPart)
if err != nil {
return header{}, headerMalformed
}
hdr.key = key
hdr.hasKey = true
}
length, keyed, delimiter, ok := parseBracketSegment(segment)
if !ok {
return header{}, headerMalformed
}
hdr.length = length
hdr.keyed = keyed
hdr.delimiter = delimiter
if strings.HasPrefix(after, "{") {
fieldsEnd := matchBrace(after)
if fieldsEnd < 0 {
return header{}, headerMalformed
}
fields, err := parseFieldList(after[1:fieldsEnd], delimiter, strict)
if err != nil {
return header{err: err}, headerMalformed
}
hdr.fields = fields
after = after[fieldsEnd+1:]
}
if !strings.HasPrefix(after, ":") {
return header{}, headerMalformed
}
hdr.inline = strings.Trim(after[1:], " ")
if hdr.keyed && hdr.fields == nil {
return header{}, headerMalformed
}
if hdr.fields != nil && hdr.inline != "" {
return header{}, headerMalformed
}
return hdr, headerOK
}
// parseBracketSegment parses "[N]", "[N<delim>]", "[N:]", or "[N:<delim>]".
func parseBracketSegment(segment string) (int, bool, Delimiter, bool) {
digits := 0
for digits < len(segment) && segment[digits] >= '0' && segment[digits] <= '9' {
digits++
}
if digits == 0 {
return 0, false, DelimiterComma, false
}
if digits > 1 && segment[0] == '0' {
// Leading zeros are not a canonical length.
return 0, false, DelimiterComma, false
}
length, err := strconv.Atoi(segment[:digits])
if err != nil {
// A length beyond int still forms a header, with a count no scope can meet.
length = math.MaxInt
}
rest := segment[digits:]
keyed := false
if strings.HasPrefix(rest, ":") {
keyed = true
rest = rest[1:]
}
delimiter := DelimiterComma
switch rest {
case "":
case "\t":
delimiter = DelimiterTab
case "|":
delimiter = DelimiterPipe
default:
return 0, false, DelimiterComma, false
}
return length, keyed, delimiter, true
}
// matchBrace returns the index of the "}" that closes the field list starting at
// index 0, ignoring braces inside quoted names.
func matchBrace(s string) int {
depth := 0
inQuotes := false
for i := 0; i < len(s); i++ {
c := s[i]
if inQuotes {
switch c {
case '\\':
i++
case '"':
inQuotes = false
}
continue
}
switch c {
case '"':
inQuotes = true
case '{':
depth++
case '}':
depth--
if depth == 0 {
return i
}
}
}
return -1
}
// parseFieldList parses the entries of a field list, recursing into nested
// field groups.
func parseFieldList(body string, delimiter Delimiter, strict bool) ([]fieldNode, error) {
if body == "" {
return nil, errors.New("empty field list")
}
if err := checkForeignDelimiters(body, delimiter); err != nil {
return nil, err
}
entries, err := splitFieldEntries(body, delimiter.rune())
if err != nil {
return nil, err
}
nodes := make([]fieldNode, 0, len(entries))
seen := make(map[string]bool, len(entries))
for _, entry := range entries {
entry = strings.Trim(entry, " ")
namePart := entry
var children []fieldNode
if brace := topLevelBrace(entry); brace >= 0 {
end := matchBrace(entry[brace:])
if end < 0 || brace+end != len(entry)-1 {
return nil, errors.New("malformed nested field group")
}
namePart = entry[:brace]
if strings.TrimRight(namePart, " \t") != namePart {