-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathparser.go
More file actions
1329 lines (1069 loc) · 34.2 KB
/
Copy pathparser.go
File metadata and controls
1329 lines (1069 loc) · 34.2 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 hocon
import (
"errors"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"text/scanner"
"time"
"unicode"
)
const (
equalsToken = "="
commaToken = ","
colonToken = ":"
dotToken = "."
objectStartToken = "{"
objectEndToken = "}"
arrayStartToken = "["
arrayEndToken = "]"
includeToken = "include"
commentToken = "#"
)
var forbiddenCharacters = map[string]bool{
"$": true, `"`: true, objectStartToken: true, objectEndToken: true, arrayStartToken: true, arrayEndToken: true,
colonToken: true, equalsToken: true, commaToken: true, "+": true, commentToken: true, "`": true, "^": true, "?": true,
"!": true, "@": true, "*": true, "&": true, `\`: true, "(": true, ")": true,
}
type parser struct {
scanner *scanner.Scanner
currentRune rune
lastConsumedWhitespaces string // used in concatenation not to lose whitespaces between values
filepath string
rootDir string // directory of the top-level parsed file, the classpath() includes are resolved against it
}
func newParser(src io.Reader) *parser {
s := newScanner(src)
currWd := "."
return &parser{scanner: s, filepath: currWd, rootDir: currWd}
}
func newFileParser(src *os.File) *parser {
s := newScanner(src)
return &parser{scanner: s, filepath: src.Name(), rootDir: path.Dir(src.Name())}
}
func newScanner(src io.Reader) *scanner.Scanner {
s := new(scanner.Scanner)
s.Init(src)
s.Whitespace ^= 1<<'\t' | 1<<' ' // do not skip tabs and spaces
s.Mode &^= scanner.ScanComments | scanner.SkipComments // do not treat the go comments ('//' and '/* */') as comments, hocon comments ('#' and '//') are handled by the parser
s.Error = func(*scanner.Scanner, string) {} // do not print errors to stderr
s.IsIdentRune = func(ch rune, i int) bool {
return ch == '_' || ch == '-' || unicode.IsLetter(ch) || unicode.IsDigit(ch) && i > 0
}
return s
}
// ParseString function parses the given hocon string, creates the configuration tree and
// returns a pointer to the Config, returns a ParseError if any error occurs while parsing
func ParseString(input string) (*Config, error) {
parser := newParser(strings.NewReader(input))
return parser.parse()
}
// ParseStringUnresolved parses the given hocon string like ParseString, but does not
// resolve the substitutions, so that the values of another config (e.g. a fallback config)
// can be used to resolve them later with the Resolve method:
//
// config, err := hocon.ParseStringUnresolved(mainConfig)
// ...
// config, err = config.WithFallback(fallbackConfig).Resolve()
func ParseStringUnresolved(input string) (*Config, error) {
parser := newParser(strings.NewReader(input))
return parser.parseUnresolved()
}
// ParseResource parses the resource at the given path, creates the configuration tree and
// returns a pointer to the Config, returns the error if any error occurs while parsing
func ParseResource(path string) (*Config, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not parse resource: %w", err)
}
return newFileParser(file).parse()
}
// ParseResourceUnresolved parses the resource at the given path like ParseResource,
// but does not resolve the substitutions, so that the values of another config
// (e.g. a fallback config) can be used to resolve them later with the Resolve method
func ParseResourceUnresolved(path string) (*Config, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not parse resource: %w", err)
}
return newFileParser(file).parseUnresolved()
}
func (p *parser) parse() (*Config, error) {
config, err := p.parseUnresolved()
if err != nil {
return nil, err
}
return config.Resolve()
}
func (p *parser) parseUnresolved() (*Config, error) {
p.advance()
if p.scanner.TokenText() == arrayStartToken {
array, err := p.extractArray()
if err != nil {
return nil, err
}
return &Config{root: array}, nil
}
object, err := p.extractObject()
if err != nil {
return nil, err
}
if token := p.scanner.TokenText(); token != "" {
return nil, invalidObjectError("invalid token "+token, p.scanner.Line, p.scanner.Column)
}
return &Config{root: object}, nil
}
func (p *parser) advance() {
p.currentRune = p.scanner.Scan()
var builder strings.Builder
for p.currentRune == '\t' || p.currentRune == ' ' {
builder.WriteRune(p.currentRune)
p.currentRune = p.scanner.Scan()
}
p.lastConsumedWhitespaces = builder.String()
}
func resolveSubstitutions(root Object, valueOptional ...Value) error {
visitedPaths := make(map[string]bool)
err := resolveAcyclicSubstitutions(root, visitedPaths, valueOptional...)
if err != nil {
return err
}
if valueOptional == nil {
if _, err := normalize(root); err != nil {
return err
}
}
return nil
}
func resolveAcyclicSubstitutions(root Object, visitedPaths map[string]bool, valueOptional ...Value) error {
var value Value
if valueOptional == nil {
value = root
} else {
value = valueOptional[0]
}
switch v := value.(type) {
case Array:
for i, value := range v {
err := processSubstitution(root, value, visitedPaths, func(foundValue Value) { v[i] = foundValue })
if err != nil {
return err
}
}
case concatenation:
for i, value := range v {
err := processSubstitution(root, value, visitedPaths, func(foundValue Value) { v[i] = foundValue })
if err != nil {
return err
}
}
case Object:
for key, value := range v {
err := processSubstitution(root, value, visitedPaths, func(foundValue Value) { v[key] = foundValue })
if err != nil {
return err
}
}
default:
return invalidValueError("substitutions are only allowed in field values and array elements", 0, 0)
}
return nil
}
func processSubstitution(root Object, value Value, visitedPaths map[string]bool, resolveFunc func(value Value)) error {
if valueType := value.Type(); valueType == SubstitutionType {
processed, err := processSubstitutionType(root, value.(*Substitution), visitedPaths)
if err != nil {
return err
}
resolveFunc(processed)
return nil
} else if valueType == valueWithAlternativeType {
withAlternative := value.(*valueWithAlternative)
if withAlternative.alternative != nil {
processed, err := processSubstitutionType(root, withAlternative.alternative, visitedPaths)
if err != nil {
return err
}
if processed != nil {
resolveFunc(processed)
return nil
}
}
// the alternative could not be resolved, fall back to the original value,
// which may itself be or contain a substitution
resolveFunc(withAlternative.value)
return processSubstitution(root, withAlternative.value, visitedPaths, resolveFunc)
} else if valueType == ObjectType || valueType == ArrayType || valueType == ConcatenationType {
return resolveAcyclicSubstitutions(root, visitedPaths, value)
}
return nil
}
func processSubstitutionType(root Object, substitution *Substitution, visitedPaths map[string]bool) (Value, error) {
if _, ok := visitedPaths[substitution.path]; ok {
return nil, errors.New("detected substitution cycle: " + substitution.String())
}
if foundValue := root.find(substitution.path); foundValue != nil {
visitedPaths[substitution.path] = true
if err := processSubstitution(root, foundValue, visitedPaths, func(v Value) { foundValue = v }); err != nil {
return nil, err
}
delete(visitedPaths, substitution.path)
if foundValue != nil {
return foundValue, nil
}
// the found value is itself an unresolved optional substitution, treat the path as undefined and fall through
}
if env, ok := os.LookupEnv(substitution.path); ok {
return String(env), nil
}
if !substitution.optional {
return nil, errors.New("could not resolve substitution: " + substitution.String() + " to a value")
}
return nil, nil
}
// normalize removes the values of the unresolved optional substitutions
// (fields, array elements and concatenation parts whose value is an undefined ${?path})
// from the configuration tree, as the hocon spec requires them to be omitted, and
// resolves the remaining concatenations: objects are merged, arrays are appended
// and string values are flattened into single String values
func normalize(value Value) (Value, error) {
switch v := value.(type) {
case Object:
for key, element := range v {
resolved, err := normalize(element)
if err != nil {
return nil, err
}
if resolved == nil {
delete(v, key)
} else {
v[key] = resolved
}
}
return v, nil
case Array:
containsNil := false
for i, element := range v {
resolved, err := normalize(element)
if err != nil {
return nil, err
}
if v[i] = resolved; v[i] == nil {
containsNil = true
}
}
if !containsNil {
return v, nil
}
result := make(Array, 0, len(v))
for _, element := range v {
if element != nil {
result = append(result, element)
}
}
return result, nil
case concatenation:
result := make(concatenation, 0, len(v))
for _, element := range v {
resolved, err := normalize(element)
if err != nil {
return nil, err
}
if resolved == nil || resolved == String("") { // empty strings do not contribute to a concatenation
continue
}
result = append(result, resolved)
}
switch {
case len(result) == 0:
return nil, nil
case len(result) == 1:
return result[0], nil
case result.containsObject():
return mergeConcatenatedObjects(result)
case result.containsArray():
return concatenateArrays(result)
default:
return flattenStrings(result), nil
}
default:
return value, nil
}
}
// mergeConcatenatedObjects merges the objects of the given concatenation into a single
// object (for the same keys the values of the later objects override the earlier ones),
// the whitespaces between the concatenated values are ignored, any other value is invalid
func mergeConcatenatedObjects(concat concatenation) (Value, error) {
merged := Object{}
for _, value := range concat {
if isWhitespaceString(value) {
continue
}
object, ok := value.(Object)
if !ok {
return nil, invalidConcatenationError()
}
mergeObjects(merged, object)
}
return merged, nil
}
// concatenateArrays appends the arrays of the given concatenation into a single array,
// the whitespaces between the concatenated values are ignored, any other value is invalid
func concatenateArrays(concat concatenation) (Value, error) {
result := Array{}
for _, value := range concat {
if isWhitespaceString(value) {
continue
}
array, ok := value.(Array)
if !ok {
return nil, invalidConcatenationError()
}
result = append(result, array...)
}
return result, nil
}
func isWhitespaceString(value Value) bool {
str, ok := value.(String)
return ok && strings.TrimSpace(string(str)) == ""
}
// flattenStrings joins the parts of the given concatenation into a single String
// value, as the hocon spec defines the result of a string value concatenation to
// be a string; returns the concatenation as it is if any of its parts is not a
// simple value (e.g. an object or an array)
func flattenStrings(concat concatenation) Value {
var builder strings.Builder
for _, element := range concat {
switch element.(type) {
case String, Int, Float32, Float64, Boolean, Duration, Null:
builder.WriteString(rawString(element))
default:
return concat
}
}
return String(builder.String())
}
func (p *parser) extractObject(isSubObject ...bool) (Object, error) {
object := Object{}
parenthesisBalanced := true
if p.scanner.TokenText() == objectStartToken {
parenthesisBalanced = false
p.advance()
if !parenthesisBalanced && p.scanner.TokenText() == objectEndToken {
parenthesisBalanced = true
p.advance()
return object, nil
}
}
lastRow := 0
// the second condition processes the last token before the end of the file, e.g. a trailing key without a value
for tok := p.scanner.Peek(); tok != scanner.EOF || p.scanner.TokenText() != ""; tok = p.scanner.Peek() {
if isComment(p.scanner.TokenText(), p.scanner.Peek()) {
p.consumeComment()
continue
}
if p.scanner.TokenText() == includeToken {
p.advance()
includedObject, err := p.parseIncludedResource()
if err != nil {
return nil, err
}
mergeObjects(object, includedObject)
p.advance()
continue
}
if !parenthesisBalanced && p.scanner.TokenText() == objectEndToken {
parenthesisBalanced = true
p.advance()
break
}
key := p.scanner.TokenText()
if !strings.HasPrefix(key, `"`) && key != dotToken {
// glue the tokens that immediately follow, as the scanner splits keys with numeric path segments like ".2g" into multiple tokens
for isAdjacentKeyRune(p.scanner.Peek()) {
p.advance()
key += p.scanner.TokenText()
}
}
key = strings.Trim(key, `"`)
if strings.HasPrefix(key, dotToken) && key != dotToken {
key = strings.TrimPrefix(key, dotToken)
}
if forbiddenCharacters[key] {
return nil, invalidKeyError(key, p.scanner.Line, p.scanner.Column)
}
if key == dotToken {
return nil, leadingPeriodError(p.scanner.Line, p.scanner.Column)
}
p.advance()
text := p.scanner.TokenText()
startsWithDot := strings.HasPrefix(text, dotToken) && text != dotToken
isNestedObjectPath := text == dotToken || text == objectStartToken || startsWithDot
if isNestedObjectPath {
if text == dotToken {
p.advance() // skip "."
if p.scanner.TokenText() == dotToken || strings.HasPrefix(p.scanner.TokenText(), dotToken) {
return nil, adjacentPeriodsError(p.scanner.Line, p.scanner.Column)
}
if isSeparator(p.scanner.TokenText(), p.scanner.Peek()) {
return nil, trailingPeriodError(p.scanner.Line, p.scanner.Column-1)
}
}
lastRow = p.scanner.Line
extractedObject, err := p.extractObject(true)
if err != nil {
return nil, err
}
if existingValue, ok := object[key]; ok {
if existingValue.Type() == ObjectType {
mergeObjects(existingValue.(Object), extractedObject)
extractedObject = existingValue.(Object)
}
}
object[key] = extractedObject
}
switch text {
case equalsToken, colonToken:
p.advance()
lastRow = p.scanner.Line
value, err := p.extractValue()
if err != nil {
return nil, err
}
if existingValue, ok := object[key]; ok {
if existingValue.Type() == ObjectType && value.Type() == ObjectType {
mergeObjects(existingValue.(Object), value.(Object))
value = existingValue
} else if (existingValue.Type() == SubstitutionType && value.Type() == SubstitutionType) ||
(existingValue.Type() == ObjectType && value.Type() == SubstitutionType) ||
(existingValue.Type() == SubstitutionType && value.Type() == ObjectType) {
value = concatenation{existingValue, value}
} else if existingValue.Type() == valueWithAlternativeType && value.Type() == SubstitutionType {
value = &valueWithAlternative{value: existingValue, alternative: value.(*Substitution)}
} else if value.Type() == SubstitutionType {
value = &valueWithAlternative{value: existingValue, alternative: value.(*Substitution)}
}
}
object[key] = value
case "+":
if p.scanner.Peek() != '=' {
return nil, invalidKeyValueSeparatorError(key, text, p.scanner.Line, p.scanner.Column)
}
p.advance()
p.advance()
err := p.parsePlusEqualsValue(object, key)
if err != nil {
return nil, err
}
default:
if !isNestedObjectPath { // a key must be followed by a separator or an object
return nil, invalidKeyValueSeparatorError(key, text, p.scanner.Line, p.scanner.Column)
}
}
for currentRow := p.scanner.Line; currentRow == lastRow && p.scanner.TokenText() != ""; currentRow = p.scanner.Line {
concatenated, err := p.checkAndConcatenate(object, key)
if err != nil {
return nil, err
}
if !concatenated {
break
}
}
if parenthesisBalanced && len(isSubObject) > 0 && isSubObject[0] {
return object, nil
}
for isComment(p.scanner.TokenText(), p.scanner.Peek()) {
p.consumeComment()
}
if p.scanner.Line == lastRow &&
p.scanner.TokenText() != commaToken &&
p.scanner.TokenText() != objectEndToken &&
p.scanner.TokenText() != "" {
return nil, missingCommaError(p.scanner.Line, p.scanner.Column)
}
if p.scanner.TokenText() == commaToken {
p.advance() // skip ","
if p.scanner.TokenText() == commaToken {
return nil, adjacentCommasError(p.scanner.Line, p.scanner.Column)
}
}
if !parenthesisBalanced && p.scanner.TokenText() == objectEndToken {
parenthesisBalanced = true
p.advance()
break
}
}
if !parenthesisBalanced {
return nil, invalidObjectError("parenthesis do not match", p.scanner.Line, p.scanner.Column)
}
return object, nil
}
func mergeObjects(existing Object, new Object) {
for key, value := range new {
existingValue, ok := existing[key]
if ok && existingValue != nil && existingValue.Type() == ObjectType && value != nil &&
value.Type() == ObjectType {
existingObj := existingValue.(Object)
mergeObjects(existingObj, value.(Object))
value = existingObj
}
if value != nil {
existing[key] = value
}
}
}
func (p *parser) parsePlusEqualsValue(existingObject Object, key string) error {
existingValue, ok := existingObject[key]
if !ok {
value, err := p.extractValue()
if err != nil {
return err
}
existingObject[key] = Array{value}
} else {
if existingValue.Type() != ArrayType {
return invalidValueError(fmt.Sprintf("value: %q of the key: %q is not an array", existingValue.String(), key), p.scanner.Line, p.scanner.Pos().Column)
}
value, err := p.extractValue()
if err != nil {
return err
}
existingObject[key] = append(existingValue.(Array), value)
}
return nil
}
func (p *parser) validateIncludeValue() (*include, error) {
var required, classpath bool
token := p.scanner.TokenText()
if token == "required" {
required = true
p.advance()
if p.scanner.TokenText() != "(" {
return nil, invalidValueError("missing opening parenthesis", p.scanner.Line, p.scanner.Column)
}
p.advance()
token = p.scanner.TokenText()
}
if token == "file" || token == "classpath" {
classpath = token == "classpath"
p.advance()
if p.scanner.TokenText() != "(" {
return nil, invalidValueError("missing opening parenthesis", p.scanner.Line, p.scanner.Column)
}
p.advance()
path := p.scanner.TokenText()
p.advance()
if p.scanner.TokenText() != ")" {
return nil, invalidValueError("missing closing parenthesis", p.scanner.Line, p.scanner.Column)
}
token = path
}
if required {
p.advance()
if p.scanner.TokenText() != ")" {
return nil, invalidValueError("missing closing parenthesis", p.scanner.Line, p.scanner.Column)
}
}
tokenLength := len(token)
if !strings.HasPrefix(token, `"`) || !strings.HasSuffix(token, `"`) || tokenLength < 2 {
return nil, invalidValueError("expected quoted string, optionally wrapped in 'file(...)' or 'classpath(...)'", p.scanner.Line, p.scanner.Column)
}
return &include{path: token[1 : tokenLength-1], classpath: classpath, required: required}, nil // remove double quotes
}
func (p *parser) parseIncludedResource() (Object, error) {
includeToken, err := p.validateIncludeValue()
if err != nil {
return nil, err
}
baseDir := path.Dir(p.filepath)
if includeToken.classpath {
// the classpath() includes are resolved against the directory of the top-level parsed file
// (as the go equivalent of the java classpath root) instead of the directory of the including file
baseDir = p.rootDir
}
includePath := path.Join(baseDir, includeToken.path)
includePaths := []string{includePath}
if path.Ext(includePath) == "" {
// an include without a file extension also includes the .json and .conf versions of the file, the values of the .conf version override the .json ones
includePaths = append(includePaths, includePath+".json", includePath+".conf")
}
includedObject := Object{}
found := false
var notExistErr error
for _, includePath := range includePaths {
object, err := p.parseIncludedFile(includePath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
if notExistErr == nil {
notExistErr = err
}
continue
}
return nil, err
}
found = true
mergeObjects(includedObject, object)
}
if !found && includeToken.required {
return nil, notExistErr
}
return includedObject, nil
}
// parseIncludedFile parses the file at the given path into an Object, inheriting the
// root directory of the current parser, the returned error wraps os.ErrNotExist if
// the file does not exist
func (p *parser) parseIncludedFile(includePath string) (includedObject Object, err error) {
file, err := os.Open(includePath)
if err != nil {
return nil, fmt.Errorf("could not parse resource: %w", err)
}
defer func() {
if closingErr := file.Close(); closingErr != nil {
err = closingErr
}
}()
includeParser := newFileParser(file)
includeParser.rootDir = p.rootDir
includeParser.advance()
if includeParser.scanner.TokenText() == arrayStartToken {
return nil, invalidValueError("included file cannot contain an array as the root value", p.scanner.Line, p.scanner.Column)
}
return includeParser.extractObject()
}
func (p *parser) checkAndConcatenate(object Object, key string) (bool, error) {
if lastValue, ok := object[key]; ok && p.canConcatenate(lastValue, p.scanner.TokenText(), p.scanner.Peek()) {
lastConsumedWhitespaces := p.lastConsumedWhitespaces
value, err := p.extractValue()
if err != nil {
return false, err
}
if lastValue.Type() == ConcatenationType {
object[key] = append(lastValue.(concatenation), String(lastConsumedWhitespaces), value)
} else {
object[key] = concatenation{lastValue, String(lastConsumedWhitespaces), value}
}
return true, nil
}
return false, nil
}
func (p *parser) checkConcatenation(lastValue Value) (Value, error) {
if p.canConcatenate(lastValue, p.scanner.TokenText(), p.scanner.Peek()) {
lastConsumedWhitespaces := p.lastConsumedWhitespaces
value, err := p.extractValue()
if err != nil {
return nil, err
}
if lastValue.Type() == ConcatenationType {
return append(lastValue.(concatenation), String(lastConsumedWhitespaces), value), nil
} else {
return concatenation{lastValue, String(lastConsumedWhitespaces), value}, nil
}
}
return nil, nil
}
func (p *parser) extractArray() (Array, error) {
if firstToken := p.scanner.TokenText(); firstToken != arrayStartToken {
return nil, invalidArrayError(fmt.Sprintf("%q is not an array start token", firstToken), p.scanner.Line, p.scanner.Column)
}
p.advance()
token := p.scanner.TokenText()
if token == commaToken {
return nil, leadingCommaError(p.scanner.Line, p.scanner.Column)
}
var array Array
if token == arrayEndToken { // empty array
p.advance()
return array, nil
}
parenthesisBalanced := false
lastRow := 0
for tok := p.scanner.Peek(); tok != scanner.EOF; tok = p.scanner.Peek() {
lastRow = p.scanner.Line
value, err := p.extractValue()
if err != nil {
return nil, err
}
token = p.scanner.TokenText()
if isComment(token, p.scanner.Peek()) {
p.consumeComment()
token = p.scanner.TokenText()
}
if p.scanner.Line == lastRow && token != commaToken && token != arrayEndToken {
concatenatedValue, err := p.checkConcatenation(value)
if err != nil {
return nil, err
}
if concatenatedValue == nil {
return nil, missingCommaError(p.scanner.Line, p.scanner.Column)
} else {
lastValue := concatenatedValue
token = p.scanner.TokenText()
for concatenatedValue != nil && token != commaToken && token != arrayEndToken {
concatenatedValue, err = p.checkConcatenation(lastValue)
if err != nil {
return nil, err
}
if concatenatedValue != nil {
lastValue = concatenatedValue
} else {
break
}
token = p.scanner.TokenText()
}
array = append(array, lastValue)
}
} else {
array = append(array, value)
}
if p.scanner.TokenText() == commaToken {
p.advance() // skip comma
token = p.scanner.TokenText()
if isComment(token, p.scanner.Peek()) {
p.consumeComment()
token = p.scanner.TokenText()
}
if token == commaToken {
return nil, adjacentCommasError(p.scanner.Line, p.scanner.Column)
}
}
if !parenthesisBalanced && token == arrayEndToken {
parenthesisBalanced = true
p.advance()
break
}
}
if !parenthesisBalanced {
return nil, invalidArrayError("parenthesis do not match", p.scanner.Line, p.scanner.Column)
}
return array, nil
}
func (p *parser) extractValue() (Value, error) {
token := p.scanner.TokenText()
if isComment(token, p.scanner.Peek()) {
p.consumeComment()
token = p.scanner.TokenText()
}
switch p.currentRune {
case scanner.Int:
if glued := p.glueAdjacent(token); glued != token {
p.advance()
return numberLedValue(glued), nil
}
value, err := strconv.Atoi(token)
if err != nil {
return nil, err
}
durationUnit := p.extractDurationUnit()
if durationUnit != 0 {
p.advance()
return Duration(time.Duration(value) * durationUnit), nil
}
return Int(value), nil
case scanner.Float:
if glued := p.glueAdjacent(token); glued != token {
p.advance()
return numberLedValue(glued), nil
}
value, err := strconv.ParseFloat(token, 64)
if err != nil {
if isUnquotedString(token) {
p.advance()
return String(token), nil
} else {
return nil, err
}
}
durationUnit := p.extractDurationUnit()
if durationUnit != 0 {
p.advance()
return Duration(time.Duration(value * float64(durationUnit))), nil
}
return Float64(value), nil
case scanner.String:
if isMultiLineString(token, p.scanner.Peek()) {
return p.extractMultiLineString()
}
p.advance()
return String(strings.Trim(token, `"`)), nil
case scanner.Ident:
token = p.glueAdjacent(token)
switch {
case token == string(null):
p.advance()
return null, nil
case isBooleanString(token):
p.advance()
return newBooleanFromString(token), nil
case isUnquotedString(token):
p.advance()
return String(token), nil
}
default:
switch {
case token == objectStartToken:
return p.extractObject()