-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathparsetoml.nim
1921 lines (1684 loc) · 65.9 KB
/
parsetoml.nim
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
## :License: MIT
##
## Introduction
## ============
## This module implements a TOML parser that is compliant with v0.5.0 of its spec.
##
## Source
## ======
## `Repo link <https://github.com/NimParsers/parsetoml>`_
##
# Copyright (c) 2015 Maurizio Tomasi and contributors
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import math
import streams
import strutils
import tables
import unicode
export tables
when (NimMajor, NimMinor, NimPatch) < (1, 4, 0):
type
IndexDefect* = IndexError
OverflowDefect* = OverflowError
Defect* = Exception
type
Sign* = enum None, Pos, Neg
TomlValueKind* {.pure.} = enum
None
Int,
Float,
Bool,
Datetime,
Date,
Time,
String,
Array,
Table
TomlDate* = object
year*: int
month*: int
day*: int
TomlTime* = object
hour*: int
minute*: int
second*: int
subsecond*: int
TomlDateTime* = object
date*: TomlDate
time*: TomlTime
case shift*: bool
of true:
isShiftPositive*: bool
zoneHourShift*: int
zoneMinuteShift*: int
of false: nil
TomlTable* = OrderedTable[string, TomlValueRef]
TomlTableRef* = ref TomlTable
TomlValueRef* = ref TomlValue
TomlValue* = object
case kind*: TomlValueKind
of TomlValueKind.None: nil
of TomlValueKind.Int: intVal*: int64
of TomlValueKind.Float:
floatVal*: float64
forcedSign*: Sign
of TomlValueKind.Bool: boolVal*: bool
of TomlValueKind.Datetime: dateTimeVal*: TomlDateTime
of TomlValueKind.Date: dateVal*: TomlDate
of TomlValueKind.Time: timeVal*: TomlTime
of TomlValueKind.String: stringVal*: string
of TomlValueKind.Array: arrayVal*: seq[TomlValueRef]
of TomlValueKind.Table: tableVal*: TomlTableRef
ParserState = object
fileName*: string
line*: int
column*: int
pushback: char
stream*: streams.Stream
curTableRef*: TomlTableRef
TomlError* = object of Defect
location*: ParserState
NumberBase = enum
base10, base16, base8, base2
StringType {.pure.} = enum
Basic, # Enclosed within double quotation marks
Literal # Enclosed within single quotation marks
const
defaultStringCapacity = 256
proc newTomlError(location: ParserState, msg: string): ref TomlError =
result = newException(TomlError, location.fileName & "(" & $location.line &
":" & $location.column & ")" & " " & msg)
result.location = location
proc getNextChar(state: var ParserState): char =
# Return the next available char from the stream associate with
# the parser state, or '\0' if there are no characters left.
if state.pushback != '\0':
# If we've just read a character without having interpreted
# it, just return it
result = state.pushback
state.pushback = '\0'
else:
if state.stream.atEnd():
return '\0'
result = state.stream.readChar()
# Update the line and column number
if result == '\l':
inc(state.line)
state.column = 1
elif result != '\r':
inc(state.column)
proc pushBackChar(state: var ParserState, c: char) {.inline.} =
state.pushback = c
type
LfSkipMode = enum
skipLf, skipNoLf
proc getNextNonWhitespace(state: var ParserState,
skip: LfSkipMode): char =
# Note: this procedure does *not* consider a newline as a
# "whitespace". Since newlines are often mandatory in TOML files
# (e.g. after a key/value specification), we do not want to miss
# them...
let whitespaces = (case skip
of skipLf: {' ', '\t', '\r', '\l'}
of skipNoLf: {' ', '\t', '\r'})
var nextChar: char
while true:
nextChar = state.getNextChar()
if nextChar == '#':
# Skip the comment up to the newline, but do not jump over it
while nextChar != '\l' and nextChar != '\0':
nextChar = state.getNextChar()
if nextChar notin whitespaces: break
result = nextChar
proc charToInt(c: char, base: NumberBase): int {.inline, noSideEffect.} =
case base
of base10, base8, base2: result = int(c) - int('0')
of base16:
if c in strutils.Digits:
result = charToInt(c, base10)
else:
result = 10 + int(toUpperAscii(c)) - int('A')
type
LeadingChar {.pure.} = enum
AllowZero, DenyZero
proc parseInt(state: var ParserState,
base: NumberBase,
leadingChar: LeadingChar): int64 =
var
nextChar: char
firstPos = true
negative = false
wasUnderscore = false
let
baseNum = (case base
of base2: 2
of base8: 8
of base10: 10
of base16: 16)
digits = (case base
of base2: {'0', '1'}
of base8: {'0', '1', '2', '3', '4', '5', '6', '7'}
of base10: strutils.Digits
of base16: strutils.HexDigits)
result = 0
while true:
wasUnderscore = nextChar == '_'
nextChar = state.getNextChar()
if nextChar == '_':
if firstPos or wasUnderscore:
raise(newTomlError(state,
"underscore must be surrounded by digit"))
continue
if nextChar in {'+', '-'} and firstPos:
firstPos = false
if nextChar == '-': negative = true
continue
if nextChar == '0' and firstPos and leadingChar == LeadingChar.DenyZero:
# TOML specifications forbid this
var upcomingChar = state.getNextChar()
if upcomingChar in Digits:
raise(newTomlError(state,
"leading zeroes are not allowed in integers"))
else:
state.pushBackChar(upcomingChar)
if nextChar notin digits:
if wasUnderscore:
raise(newTomlError(state,
"underscore must be surrounded by digit"))
state.pushBackChar(nextChar)
break
try:
result = result * baseNum - charToInt(nextChar, base)
except OverflowDefect:
raise(newTomlError(state,
"integer numbers wider than 64 bits not allowed"))
firstPos = false
if not negative:
try:
result = -result
except OverflowDefect:
raise(newTomlError(state,
"integer numbers wider than 64 bits not allowed"))
proc parseEncoding(state: var ParserState): TomlValueRef =
let nextChar = state.getNextChar()
case nextChar:
of 'b':
return TomlValueRef(kind: TomlValueKind.Int, intVal: parseInt(state, base2, LeadingChar.AllowZero))
of 'o':
return TomlValueRef(kind: TomlValueKind.Int, intVal: parseInt(state, base8, LeadingChar.AllowZero))
of 'x':
return TomlValueRef(kind: TomlValueKind.Int, intVal: parseInt(state, base16, LeadingChar.AllowZero))
else: raise newTomlError(state, "illegal character")
proc parseDecimalPart(state: var ParserState): float64 =
var
nextChar: char
invPowerOfTen = 10.0
firstPos = true
wasUnderscore = false
result = 0.0
while true:
wasUnderscore = nextChar == '_'
nextChar = state.getNextChar()
if nextChar == '_':
if firstPos or wasUnderscore:
raise(newTomlError(state,
"underscore must be surrounded by digit"))
continue
if nextChar notin strutils.Digits:
if wasUnderscore:
raise(newTomlError(state,
"underscore must be surrounded by digit"))
state.pushBackChar(nextChar)
if firstPos:
raise newTomlError(state, "decimal part empty")
break
result = result + (int(nextChar) - int('0')).float / invPowerOfTen
invPowerOfTen *= 10
firstPos = false
proc stringDelimiter(kind: StringType): char {.inline, noSideEffect.} =
result = (case kind
of StringType.Basic: '\"'
of StringType.Literal: '\'')
proc parseUnicode(state: var ParserState): string =
let
escapeKindChar = state.getNextChar()
oldState = (column: state.column, line: state.line)
code = parseInt(state, base16, LeadingChar.AllowZero)
if state.line != oldState.line:
raise newTomlError(state, "invalid Unicode codepoint, can't span lines")
if escapeKindChar == 'u' and state.column - 5 != oldState.column:
raise newTomlError(state, "invalid Unicode codepoint, 'u' must have " &
"four character value")
if escapeKindChar == 'U' and state.column - 9 != oldState.column:
raise newTomlError(state, "invalid Unicode codepoint, 'U' must have " &
"eight character value")
if code notin 0'i64..0xD7FF and code notin 0xE000'i64..0x10FFFF:
raise(newTomlError(state, "invalid Unicode codepoint, " &
"must be a Unicode scalar value"))
return unicode.toUTF8(Rune(code))
proc parseEscapeChar(state: var ParserState, escape: char): string =
case escape
of 'b': result = "\b"
of 't': result = "\t"
of 'n': result = "\l"
of 'f': result = "\f"
of 'r': result = "\r"
of '\'': result = "\'"
of '\"': result = "\""
of '\\': result = "\\"
of 'u', 'U':
state.pushBackChar(escape)
result = parseUnicode(state)
else:
raise(newTomlError(state,
"unknown escape " &
"sequence \"\\" & escape & "\""))
proc parseSingleLineString(state: var ParserState, kind: StringType): string =
# This procedure parses strings enclosed within single/double
# quotation marks. It assumes that the quotation mark has already
# been consumed by the "state" variable, which therefore is ready
# to read the first character of the string.
result = newStringOfCap(defaultStringCapacity)
let delimiter = stringDelimiter(kind)
var nextChar: char
while true:
nextChar = state.getNextChar()
if nextChar == delimiter:
break
if nextChar == '\0':
raise(newTomlError(state, "unterminated string"))
if ord(nextChar) in {16, 31, 127}:
raise(newTomlError(state, "invalid character in string, ord: " & $ord(nextChar)))
if nextChar == '\\' and kind == StringType.Basic:
nextChar = state.getNextChar()
result.add(state.parseEscapeChar(nextChar))
continue
result.add(nextChar)
proc parseMultiLineString(state: var ParserState, kind: StringType): string =
# This procedure parses strings enclosed within three consecutive
# sigle/double quotation marks. It assumes that all the quotation
# marks have already been consumed by the "state" variable, which
# therefore is ready to read the first character of the string.
result = newStringOfCap(defaultStringCapacity)
let delimiter = stringDelimiter(kind)
var
isFirstChar = true
nextChar: char
while true:
nextChar = state.getNextChar()
# Skip the first newline, if it comes immediately after the
# quotation marks
if isFirstChar and (nextChar == '\l'):
isFirstChar = false
continue
if nextChar == delimiter:
# Are we done?
nextChar = state.getNextChar()
if nextChar == delimiter:
nextChar = state.getNextChar()
if nextChar == delimiter:
# Done with this string
return
else:
# Just got a double delimiter
result.add(delimiter & delimiter)
state.pushBackChar(nextChar)
continue
else:
# Just got a lone delimiter
result.add(delimiter)
state.pushBackChar(nextChar)
continue
if nextChar == '\\' and kind == StringType.Basic:
# This can either be an escape sequence or a end-of-line char
nextChar = state.getNextChar()
if nextChar in {'\l', '\r', ' '}:
# We're at the end of a line: skip everything till the
# next non-whitespace character
while nextChar in {'\l', '\r', ' ', '\t'}:
nextChar = state.getNextChar()
state.pushBackChar(nextChar)
continue
else:
# This is just an escape sequence (like "\t")
#nextChar = state.getNextChar()
result.add(state.parseEscapeChar(nextChar))
continue
if nextChar == '\0':
raise(newTomlError(state, "unterminated string"))
if ord(nextChar) in {16, 31, 127}:
raise(newTomlError(state, "invalid character in string, ord: " & $ord(nextChar)))
result.add(nextChar)
isFirstChar = false
proc parseString(state: var ParserState, kind: StringType): string =
## This function assumes that "state" has already consumed the
## first character (either \" or \', which is passed in the
## "openChar" parameter).
let delimiter = stringDelimiter(kind)
var nextChar: char = state.getNextChar()
if nextChar == delimiter:
# We have two possibilities here: (1) the empty string, or (2)
# "long" multi-line strings.
nextChar = state.getNextChar()
if nextChar == delimiter:
return parseMultiLineString(state, kind)
else:
# Empty string. This was easy!
state.pushBackChar(nextChar)
return ""
else:
state.pushBackChar(nextChar)
return parseSingleLineString(state, kind)
# Forward declaration
proc parseValue(state: var ParserState): TomlValueRef
proc parseInlineTable(state: var ParserState): TomlValueRef
proc parseArray(state: var ParserState): seq[TomlValueRef] =
# This procedure assumes that "state" has already consumed the '['
# character
result = newSeq[TomlValueRef](0)
while true:
var nextChar: char = state.getNextNonWhitespace(skipLf)
case nextChar
of ']':
return
of ',':
if len(result) == 0:
# This happens with "[, 1, 2]", for instance
raise(newTomlError(state, "first array element missing"))
# Check that this is not a terminating comma (like in
# "[b,]")
nextChar = state.getNextNonWhitespace(skipLf)
if nextChar == ']':
return
state.pushBackChar(nextChar)
else:
let oldState = state # Saved for error messages
var newValue: TomlValueRef
if nextChar != '{':
state.pushBackChar(nextChar)
newValue = parseValue(state)
else:
newValue = parseInlineTable(state)
if len(result) > 0:
# Check that the type of newValue is compatible with the
# previous ones
if newValue.kind != result[low(result)].kind:
raise(newTomlError(oldState,
"array members with incompatible types"))
result.add(newValue)
proc parseStrictNum(state: var ParserState,
minVal: int,
maxVal: int,
count: Slice[int],
msg: string): int =
var
nextChar: char
parsedChars = 0
result = 0
while true:
nextChar = state.getNextChar()
if nextChar notin strutils.Digits:
state.pushBackChar(nextChar)
break
try:
result = result * 10 + charToInt(nextChar, base10)
parsedChars += 1
except OverflowDefect:
raise(newTomlError(state,
"integer numbers wider than 64 bits not allowed"))
if parsedChars notin count:
raise(newTomlError(state,
"too few or too many characters in digit, expected " &
$count & " got " & $parsedChars))
if result < minVal or result > maxVal:
raise(newTomlError(state, msg & " (" & $result & ")"))
template parseStrictNum(state: var ParserState,
minVal: int,
maxVal: int,
count: int,
msg: string): int =
parseStrictNum(state, minVal, maxVal, (count..count), msg)
proc parseTimePart(state: var ParserState, val: var TomlTime) =
var
nextChar: char
curLine = state.line
# Parse the minutes
val.minute = parseStrictNum(state, minVal = 0, maxVal = 59, count = 2,
"number out of range for minutes")
if curLine != state.line:
raise(newTomlError(state, "invalid date field, stopped in or after minutes field"))
nextChar = state.getNextChar()
if nextChar != ':':
raise(newTomlError(state,
"\":\" expected after the number of seconds"))
# Parse the second. Note that seconds=60 *can* happen (leap second)
val.second = parseStrictNum(state, minVal = 0, maxVal = 60, count = 2,
"number out of range for seconds")
nextChar = state.getNextChar()
if nextChar == '.':
val.subsecond = parseInt(state, base10, LeadingChar.AllowZero).int
else:
state.pushBackChar(nextChar)
proc parseDateTimePart(state: var ParserState,
dateTime: var TomlDateTime): bool =
# This function is called whenever a datetime object is found. They follow
# an ISO convention and can use one of the following format:
#
# - YYYY-MM-DDThh:mm:ss[+-]hh:mm
# - YYYY-MM-DDThh:mm:ssZ
#
# where the "T" and "Z" letters are literals, [+-] indicates
# *either* "+" or "-", YYYY is the 4-digit year, MM is the 2-digit
# month, DD is the 2-digit day, hh is the 2-digit hour, mm is the
# 2-digit minute, and ss is the 2-digit second. The hh:mm after
# the +/- character is the timezone; a literal "Z" indicates the
# local timezone.
# This function assumes that the "YYYY-" part has already been
# parsed (this happens because during parsing, finding a 4-digit
# number like "YYYY" might just indicate the presence of an
# integer or a floating-point number; it's the following "-" that
# tells the parser that the value is a datetime). As a consequence
# of this, we assume that "dateTime.year" has already been set.
var
nextChar: char
curLine = state.line
# Parse the month
dateTime.date.month = parseStrictNum(state, minVal = 1, maxVal = 12, count = 2,
"number out of range for the month")
if curLine != state.line:
raise(newTomlError(state, "invalid date field, stopped in or after month field"))
nextChar = state.getNextChar()
if nextChar != '-':
raise(newTomlError(state, "\"-\" expected after the month number"))
# Parse the day
dateTime.date.day = parseStrictNum(state, minVal = 1, maxVal = 31, count = 2,
"number out of range for the day")
if curLine != state.line:
return false
else:
nextChar = state.getNextChar()
if nextChar notin {'t', 'T', ' '}:
raise(newTomlError(state, "\"T\", \"t\", or space expected after the day number"))
# Parse the hour
dateTime.time.hour = parseStrictNum(state, minVal = 0, maxVal = 23, count = 2,
"number out of range for the hours")
if curLine != state.line:
raise(newTomlError(state, "invalid date field, stopped in or after hours field"))
nextChar = state.getNextChar()
if nextChar != ':':
raise(newTomlError(state, "\":\" expected after the number of hours"))
# Parse the minutes
dateTime.time.minute = parseStrictNum(state, minVal = 0, maxVal = 59, count = 2,
"number out of range for minutes")
if curLine != state.line:
raise(newTomlError(state, "invalid date field, stopped in or after minutes field"))
nextChar = state.getNextChar()
if nextChar != ':':
raise(newTomlError(state,
"\":\" expected after the number of seconds"))
# Parse the second. Note that seconds=60 *can* happen (leap second)
dateTime.time.second = parseStrictNum(state, minVal = 0, maxVal = 60, count = 2,
"number out of range for seconds")
nextChar = state.getNextChar()
if nextChar == '.':
dateTime.time.subsecond = parseInt(state, base10, LeadingChar.AllowZero).int
else:
state.pushBackChar(nextChar)
nextChar = state.getNextChar()
case nextChar
of 'z', 'Z':
dateTime = TomlDateTime(
time: dateTime.time,
date: dateTime.date,
shift: true,
isShiftPositive: true,
zoneHourShift: 0,
zoneMinuteShift: 0
)
of '+', '-':
dateTime = TomlDateTime(
time: dateTime.time,
date: dateTime.date,
shift: true,
isShiftPositive: (nextChar == '+')
)
dateTime.zoneHourShift =
parseStrictNum(state, minVal = 0, maxVal = 23, count = 2,
"number out of range for shift hours")
if curLine != state.line:
raise(newTomlError(state, "invalid date field, stopped in or after shift hours field"))
nextChar = state.getNextChar()
if nextChar != ':':
raise(newTomlError(state,
"\":\" expected after the number of shift hours"))
dateTime.zoneMinuteShift =
parseStrictNum(state, minVal = 0, maxVal = 59, count = 2,
"number out of range for shift minutes")
else:
if curLine == state.line:
raise(newTomlError(state, "unexpected character " & escape($nextChar) &
" instead of the time zone"))
else: # shift is automatically initialized to false
state.pushBackChar(nextChar)
return true
proc parseDateOrTime(state: var ParserState, digits: int, yearOrHour: int): TomlValueRef =
var
nextChar: char
yoh = yearOrHour
d = digits
while true:
nextChar = state.getNextChar()
case nextChar:
of ':':
if d != 2:
raise newTomlError(state, "wrong number of characters for hour")
var val: TomlTime
val.hour = yoh
parseTimePart(state, val)
return TomlValueRef(kind: TomlValueKind.Time, timeVal: val)
of '-':
if d != 4:
raise newTomlError(state, "wrong number of characters for year")
var val: TomlDateTime
val.date.year = yoh
let fullDate = parseDateTimePart(state, val)
if fullDate:
return TomlValueRef(kind: TomlValueKind.DateTime,
dateTimeVal: val)
else:
return TomlValueRef(kind: TomlValueKind.Date,
dateVal: val.date)
of strutils.Digits:
if d == 4:
raise newTomlError(state, "leading zero not allowed")
try:
yoh *= 10
yoh += ord(nextChar) - ord('0')
d += 1
except OverflowDefect:
raise newTomlError(state, "number larger than 64 bits wide")
continue
of strutils.Whitespace:
raise newTomlError(state, "leading zero not allowed")
else: raise newTomlError(state, "illegal character")
break
proc parseFloat(state: var ParserState, intPart: int, forcedSign: Sign): TomlValueRef =
var
decimalPart = parseDecimalPart(state)
nextChar = state.getNextChar()
exponent: int64 = 0
if nextChar in {'e', 'E'}:
exponent = parseInt(state, base10, LeadingChar.AllowZero)
else:
state.pushBackChar(nextChar)
let value =
if intPart <= 0:
pow(10.0, exponent.float64) * (float64(intPart) - decimalPart)
else:
pow(10.0, exponent.float64) * (float64(intPart) + decimalPart)
return TomlValueRef(kind: TomlValueKind.Float, floatVal: if forcedSign != Neg: -value else: value, forcedSign: forcedSign)
proc parseNumOrDate(state: var ParserState): TomlValueRef =
var
nextChar: char
forcedSign: Sign = None
while true:
nextChar = state.getNextChar()
case nextChar:
of '0':
nextChar = state.getNextChar()
if forcedSign == None:
if nextChar in {'b', 'x', 'o'}:
state.pushBackChar(nextChar)
return parseEncoding(state)
else:
# This must now be a float or a date/time, or a sole 0
case nextChar:
of '.':
return parseFloat(state, 0, forcedSign)
of strutils.Whitespace:
state.pushBackChar(nextChar)
return TomlValueRef(kind: TomlValueKind.Int, intVal: 0)
of strutils.Digits:
# This must now be a date/time
return parseDateOrTime(state, digits = 2, yearOrHour = ord(nextChar) - ord('0'))
else:
# else is a sole 0
return TomlValueRef(kind: TomlValueKind.Int, intVal: 0)
else:
# This must now be a float, or a sole 0
case nextChar:
of '.':
return parseFloat(state, 0, forcedSign)
of strutils.Whitespace:
state.pushBackChar(nextChar)
return TomlValueRef(kind: TomlValueKind.Int, intVal: 0)
else:
# else is a sole 0
return TomlValueRef(kind: TomlValueKind.Int, intVal: 0)
of strutils.Digits - {'0'}:
# This might be a date/time, or an int or a float
var
digits = 1
curSum = ord('0') - ord(nextChar)
wasUnderscore = false
while true:
nextChar = state.getNextChar()
if wasUnderscore and nextChar notin strutils.Digits:
raise newTomlError(state, "underscores must be surrounded by digits")
case nextChar:
of ':':
if digits != 2:
raise newTomlError(state, "wrong number of characters for hour")
var val: TomlTime
val.hour = -curSum
parseTimePart(state, val)
return TomlValueRef(kind: TomlValueKind.Time, timeVal: val)
of '-':
if digits != 4:
raise newTomlError(state, "wrong number of characters for year")
var val: TomlDateTime
val.date.year = -curSum
let fullDate = parseDateTimePart(state, val)
if fullDate:
return TomlValueRef(kind: TomlValueKind.DateTime,
dateTimeVal: val)
else:
return TomlValueRef(kind: TomlValueKind.Date,
dateVal: val.date)
of '.':
return parseFloat(state, curSum, forcedSign)
of 'e', 'E':
var exponent = parseInt(state, base10, LeadingChar.AllowZero)
let value = pow(10.0, exponent.float64) * float64(curSum)
return TomlValueRef(kind: TomlValueKind.Float, floatVal: if forcedSign != Neg: -value else: value)
of strutils.Digits:
try:
curSum *= 10
curSum += ord('0') - ord(nextChar)
digits += 1
except OverflowDefect:
raise newTomlError(state, "number larger than 64 bits wide")
wasUnderscore = false
continue
of '_':
wasUnderscore = true
continue
of strutils.Whitespace:
state.pushBackChar(nextChar)
return TomlValueRef(kind: TomlValueKind.Int, intVal: if forcedSign != Neg: -curSum else: curSum)
else:
state.pushBackChar(nextChar)
return TomlValueRef(kind: TomlValueKind.Int, intVal: if forcedSign != Neg: -curSum else: curSum)
break
of '+', '-':
forcedSign = if nextChar == '+': Pos else: Neg
continue
of 'i':
# Is this "inf"?
let oldState = state
if state.getNextChar() != 'n' or
state.getNextChar() != 'f':
raise(newTomlError(oldState, "unknown identifier"))
return TomlValueRef(kind: TomlValueKind.Float, floatVal: if forcedSign == Neg: NegInf else: Inf, forcedSign: forcedSign)
of 'n':
# Is this "nan"?
let oldState = state
if state.getNextChar() != 'a' or
state.getNextChar() != 'n':
raise(newTomlError(oldState, "unknown identifier"))
return TomlValueRef(kind: TomlValueKind.Float, floatVal: NaN, forcedSign: forcedSign)
else:
raise newTomlError(state, "illegal character " & escape($nextChar))
break
proc parseValue(state: var ParserState): TomlValueRef =
var nextChar: char
nextChar = state.getNextNonWhitespace(skipNoLf)
case nextChar
of strutils.Digits, '+', '-', 'i', 'n':
state.pushBackChar(nextChar)
return parseNumOrDate(state)
of 't':
# Is this "true"?
let oldState = state # Only used for error messages
if state.getNextChar() != 'r' or
state.getNextChar() != 'u' or
state.getNextChar() != 'e':
raise(newTomlError(oldState, "unknown identifier"))
result = TomlValueRef(kind: TomlValueKind.Bool, boolVal: true)
of 'f':
# Is this "false"?
let oldState = state # Only used for error messages
if state.getNextChar() != 'a' or
state.getNextChar() != 'l' or
state.getNextChar() != 's' or
state.getNextChar() != 'e':
raise(newTomlError(oldState, "unknown identifier"))
result = TomlValueRef(kind: TomlValueKind.Bool, boolVal: false)
of '\"':
# A basic string (accepts \ escape codes)
result = TomlValueRef(kind: TomlValueKind.String,
stringVal: parseString(state, StringType.Basic))
of '\'':
# A literal string (does not accept \ escape codes)
result = TomlValueRef(kind: TomlValueKind.String,
stringVal: parseString(state, StringType.Literal))
of '[':
# An array
result = TomlValueRef(kind: TomlValueKind.Array,
arrayVal: parseArray(state))
else:
raise(newTomlError(state,
"unexpected character " & escape($nextChar)))
proc parseName(state: var ParserState): string =
# This parses the name of a key or a table
result = newStringOfCap(defaultStringCapacity)
var nextChar = state.getNextNonWhitespace(skipNoLf)
if nextChar == '\"':
return state.parseString(StringType.Basic)
elif nextChar == '\'':
return state.parseString(StringType.Literal)
state.pushBackChar(nextChar)
while true:
nextChar = state.getNextChar()
if (nextChar in {'=', '.', '[', ']', '\0', ' ', '\t'}):
# Any of the above characters marks the end of the name
state.pushBackChar(nextChar)
break
elif (nextChar notin {'a'..'z', 'A'..'Z', '0'..'9', '_', '-'}):
raise(newTomlError(state,
"bare key has illegal character: " & escape($nextChar)))
else:
result.add(nextChar)
type
BracketType {.pure.} = enum
single, double
proc parseTableName(state: var ParserState,
brackets: BracketType): seq[string] =
# This code assumes that '[' has already been consumed
result = newSeq[string](0)
while true:
#let partName = state.parseName(SpecialChars.AllowNumberSign)
var
nextChar = state.getNextChar()
partName: string
if nextChar == '"':
partName = state.parseString(StringType.Basic)
else:
state.pushBackChar(nextChar)
partName = state.parseName()
result.add(partName)
nextChar = state.getNextNonWhitespace(skipNoLf)
case nextChar
of ']':
if brackets == BracketType.double:
nextChar = state.getNextChar()
if nextChar != ']':
raise(newTomlError(state,
"\"]]\" expected"))
# We must check that there is nothing else in this line
nextChar = state.getNextNonWhitespace(skipNoLf)
if nextChar notin {'\l', '\0'}:
raise(newTomlError(state,
"unexpected character " & escape($nextChar)))
break
of '.': continue
else:
raise(newTomlError(state,
"unexpected character " & escape($nextChar)))
proc setEmptyTableVal(val: var TomlValueRef) =
val = TomlValueRef(kind: TomlValueKind.Table)
new(val.tableVal)
val.tableVal[] = initOrderedTable[string, TomlValueRef]()
proc parseInlineTable(state: var ParserState): TomlValueRef =
new(result)
setEmptyTableVal(result)
var firstComma = true
while true:
var nextChar = state.getNextNonWhitespace(skipNoLf)
case nextChar
of '}':
return
of ',':
if firstComma:
raise(newTomlError(state, "first inline table element missing"))
# Check that this is not a terminating comma (like in
# "[b,]")
nextChar = state.getNextNonWhitespace(skipNoLf)
if nextChar == '}':
return
state.pushBackChar(nextChar)
of '\n':
raise(newTomlError(state, "inline tables cannot contain newlines"))