-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToml.gr
1881 lines (1853 loc) · 56.5 KB
/
Toml.gr
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
module Toml
from "string" include String
from "char" include Char
from "list" include List
from "buffer" include Buffer
from "uint8" include Uint8
from "number" include Number
from "array" include Array
from "Set" include Set
// TODO: Remove this
from "map" include Map
from "runtime/unsafe/wasmi32" include WasmI32
from "runtime/numberUtils" include NumberUtils
from "runtime/string" include String as RunTimeString
from "runtime/numbers" include Numbers
from "runtime/dataStructures" include DataStructures
use RunTimeString.{ toString as runtimeToString }
use Numbers.{ coerceNumberToWasmI32 }
use DataStructures.{ tagSimpleNumber }
// Types
enum NumberOrDateOrTime {
IsNumberLiteral,
IsDateLiteral,
IsTimeLiteral,
}
enum TableKeyHolds {
KeyHoldsArray,
KeyHoldsTable,
KeyHoldsValue,
}
provide enum rec Toml {
TomlTable(List<(String, Toml)>),
TomlArray(List<Toml>),
TomlString(String),
TomlInt(Number),
TomlFloat(Number),
TomlBool(Bool),
TomlDateTime(String),
TomlDateTimeLocal(String),
TomlDateLocal(String),
TomlTimeLocal(String),
}
/**
* Represents errors for TOML parsing along with a human readable text message.
*/
provide enum TOMLParseError {
UnexpectedEndOfInput(String),
UnexpectedToken(String),
// TODO: Add Error Messages To All Of These, Along With Positions
UnexpectedEndOfString,
TomlInvalidTableWrite,
TomlInvalidKey,
DuplicateTomlKey,
// TODO: Use A String Here Holding The U+xxxxxx value
InvalidUnicodeScalar(Number),
InvalidDateTime(String),
}
/**
* Internal data structure used during parsing.
*/
record TOMLParserState {
string: String,
bufferParse: Buffer.Buffer,
mut currentCodePoint: Number,
mut pos: Number,
mut bytePos: Number,
}
exception MalformedUnicode
// Internals
let saveTomlState = parserState => {
(parserState.currentCodePoint, parserState.pos, parserState.bytePos)
}
let restoreTomlState = ((currentCodePoint, pos, bytePos), parserState) => {
parserState.currentCodePoint = currentCodePoint
parserState.pos = pos
parserState.bytePos = bytePos
}
let _END_OF_INPUT = -1
@unsafe
let toHex = (n: Number) => {
let x = coerceNumberToWasmI32(n)
NumberUtils.itoa32(x, 16n)
}
let toHexWithZeroPadding = (n: Number, padTo: Number) => {
// Note that this function is only called in exceptional cases so no effort
// was made to optimize it.
let mut result = toHex(n)
while (String.length(result) < padTo) {
result = "0" ++ result
}
result
}
let formatCodePointOrEOF = (codePoint: Number) => {
if (codePoint >= 32 && codePoint <= 126) {
// If the codepoint is in the range of printable ASCII charactes, then
// display the character itself . Whether it's a good idea to display
// all of them, especially space is up for debate.
"'" ++ runtimeToString(Char.fromCode(codePoint)) ++ "'"
} else if (codePoint == -1) {
// Special case for value used by the parsing code to avoid heap allocations.
"end of input"
} else {
// Format any other code point as hexadecimal value.
"U+" ++ toHexWithZeroPadding(codePoint, 4)
}
}
// TODO: Make this take unexpected and expected for better consistency
let buildUnexpectedTokenError = (parserState: TOMLParserState, detail: String) => {
let codePoint = parserState.currentCodePoint
let pos = parserState.pos
if (codePoint == _END_OF_INPUT) {
UnexpectedEndOfInput(
"Unexpected token at position " ++ runtimeToString(pos) ++ ": " ++ detail,
)
} else {
UnexpectedToken(
"Unexpected token at position " ++ runtimeToString(pos) ++ ": " ++ detail,
)
}
}
// This function has been copied from the String module as a temporary
// solution. This will likely be replaced by a more robust solution for
// iterating over strings in the near future.
@unsafe
let getCodePoint = (ptr: WasmI32) => {
// Algorithm from https://encoding.spec.whatwg.org/#utf-8-decoder
use WasmI32.{ (+), (&), (|), (<<), leU as (<=), geU as (>=), (==) }
let mut codePoint = 0n
let mut bytesSeen = 0n
let mut bytesNeeded = 0n
let mut lowerBoundary = 0x80n
let mut upperBoundary = 0xBFn
let mut offset = 0n
while (true) {
let byte = WasmI32.load8U(ptr + offset, 0n)
offset += 1n
if (bytesNeeded == 0n) {
if (byte >= 0x00n && byte <= 0x7Fn) {
return byte
} else if (byte >= 0xC2n && byte <= 0xDFn) {
bytesNeeded = 1n
codePoint = byte & 0x1Fn
} else if (byte >= 0xE0n && byte <= 0xEFn) {
if (byte == 0xE0n) lowerBoundary = 0xA0n
if (byte == 0xEDn) upperBoundary = 0x9Fn
bytesNeeded = 2n
codePoint = byte & 0xFn
} else if (byte >= 0xF0n && byte <= 0xF4n) {
if (byte == 0xF0n) lowerBoundary = 0x90n
if (byte == 0xF4n) upperBoundary = 0x8Fn
bytesNeeded = 3n
codePoint = byte & 0x7n
} else {
throw MalformedUnicode
}
continue
}
if (!(lowerBoundary <= byte && byte <= upperBoundary)) {
throw MalformedUnicode
}
lowerBoundary = 0x80n
upperBoundary = 0xBFn
codePoint = codePoint << 6n | byte & 0x3Fn
bytesSeen += 1n
if (bytesSeen == bytesNeeded) {
return codePoint
}
}
return 0n
}
@unsafe
let rec readCodePoint = (bytePosition: Number, string: String) => {
use WasmI32.{ (+), ltU as (<) }
let strPtr = WasmI32.fromGrain(string)
let byteSize = WasmI32.load(strPtr, 4n)
let bytePositionW32 = coerceNumberToWasmI32(bytePosition)
let ptr = strPtr + 8n + bytePositionW32
let mut idx = 0n
if (bytePositionW32 < byteSize) {
let codePoint = getCodePoint(ptr)
tagSimpleNumber(codePoint)
} else {
_END_OF_INPUT
}
}
let codePointUTF8ByteCount = (usv: Number) => {
if (!Char.isValid(usv)) {
throw InvalidArgument("Invalid unicode scalar value")
}
if (usv <= 127) {
1
} else if (usv <= 2047) {
2
} else if (usv <= 65535) {
3
} else {
4
}
}
let isAtEndOfInput = (parserState: TOMLParserState) => {
parserState.currentCodePoint == _END_OF_INPUT
}
let next = (parserState: TOMLParserState) => {
let mut c = parserState.currentCodePoint
if (c != _END_OF_INPUT) {
parserState.bytePos += codePointUTF8ByteCount(c)
c = readCodePoint(parserState.bytePos, parserState.string)
parserState.currentCodePoint = c
parserState.pos += 1
}
c
}
let expectCodePointAndAdvance = (
expectedCodePoint: Number,
parserState: TOMLParserState,
) => {
let c = parserState.currentCodePoint
if (c == expectedCodePoint) {
next(parserState)
None
} else {
let detail = "expected " ++
formatCodePointOrEOF(expectedCodePoint) ++
", found " ++
formatCodePointOrEOF(c)
Some(buildUnexpectedTokenError(parserState, detail))
}
}
let isCurrentTokenNewLine = (parserState: TOMLParserState) => {
match (parserState.currentCodePoint) {
0x0A => true, // line feed
0x0D => { // carriage return
let startState = saveTomlState(parserState)
next(parserState)
let isCRLF = parserState.currentCodePoint == 0x0A
restoreTomlState(startState, parserState)
isCRLF
},
_ => false,
}
}
let isCurrentTokenSpace = (parserState: TOMLParserState) => {
match (parserState.currentCodePoint) {
0x09 => true, // tab
0x20 => true, // space
_ => false,
}
}
let isCurrentTokenWhiteSpace = (parserState: TOMLParserState) => {
isCurrentTokenSpace(parserState) || isCurrentTokenNewLine(parserState)
}
let isValidTomlChar = (codePoint: Number) => {
let mut isValid = false
// Ranges To Allow
if (codePoint >= 0x01 && codePoint <= 0x09) isValid = true
if (codePoint >= 0x0E && codePoint <= 0x7F) isValid = true
if (codePoint >= 0x80 && codePoint <= 0xD7FF) isValid = true
if (codePoint >= 0xE000 && codePoint <= 0x10FFFF) isValid = true
// Ranges To Disallow
// TODO: Determine what code points should actually be disallowed, I think its here https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf#G7404
if (codePoint == 0xFFFD) isValid = false
// Ensure Valid Grain Char
if (!Char.isValid(codePoint)) isValid = false
// Default True
return isValid
}
let isValidCommentChar = (codePoint: Number) => {
if (!isValidTomlChar(codePoint)) return false
if (codePoint == 0x00 || codePoint >= 0x0A && codePoint <= 0x0D) return false
return true
}
let skipNewLine = (parserState: TOMLParserState) => {
// isAtEndOfInput is not strictly necessary here
// could remove as an optimization
while (isCurrentTokenNewLine(parserState) && !isAtEndOfInput(parserState)) {
if (parserState.currentCodePoint == 0x0D) { // '\r'
next(parserState)
void
}
next(parserState)
void
}
}
let skipSpace = (parserState: TOMLParserState) => {
// isAtEndOfInput is not strictly necessary here
// could remove as an optimization
while (isCurrentTokenSpace(parserState) && !isAtEndOfInput(parserState)) {
next(parserState)
void
}
}
let skipWhiteSpace = (parserState: TOMLParserState) => {
// isAtEndOfInput is not strictly necessary here
// could remove as an optimization
while (isCurrentTokenWhiteSpace(parserState) && !isAtEndOfInput(parserState)) {
next(parserState)
void
}
}
let addCharFromCodePoint = (codePoint: Number, buffer: Buffer.Buffer) => {
Buffer.addChar(Char.fromCode(codePoint), buffer)
}
let atoiFast = buffer => {
let bufLen = Buffer.length(buffer)
let mut result = 0
for (let mut i = 0; i < bufLen; i += 1) {
use Uint8.{ (-) }
result = (result << 1) +
(result << 3) +
Uint8.toNumber(Buffer.getUint8(i, buffer) - 48us)
}
result
}
// Validation Functions
let isLeapYear = year => {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
let isValidDateInMonth = (year, month, day) => {
match (month) {
01 => day >= 1 && day <= 31,
02 => {
if (isLeapYear(year)) {
day >= 1 && day <= 29
} else {
day >= 1 && day <= 28
}
},
03 => day >= 1 && day <= 31,
04 => day >= 1 && day <= 30,
05 => day >= 1 && day <= 31,
06 => day >= 1 && day <= 30,
07 => day >= 1 && day <= 31,
08 => day >= 1 && day <= 31,
09 => day >= 1 && day <= 30,
10 => day >= 1 && day <= 31,
11 => day >= 1 && day <= 30,
12 => day >= 1 && day <= 31,
_ => false,
}
}
// Toml Table
let rec writeTable = (
tablePath,
tableElement,
rootTable,
writeArray,
overWrite=true,
) => {
match (tablePath) {
[pathItem] when writeArray => {
match (rootTable) {
TomlTable(tableItems) => {
// Find Path Item
let pathItemIndex = List.findIndex(
((key, _)) => key == pathItem,
tableItems
)
let (tableKey, tableValue) = match (pathItemIndex) {
Some(pathItemIndex) => {
match (List.nth(pathItemIndex, tableItems)) {
Some(item) => item,
None => fail "Impossible5",
}
},
None => (pathItem, TomlArray([])),
}
// Ensure Our Value Is an Array
match (tableValue) {
TomlArray(arrItems) => {
// TODO: Find a more efficent way of doing this
let arrItems = List.append(arrItems, [tableElement])
let tableItems = match (pathItemIndex) {
Some(pathItemIndex) => {
// TODO: Find a faster way todo this
let arr = Array.fromList(tableItems)
arr[pathItemIndex] = (pathItem, TomlArray(arrItems))
Array.toList(arr)
},
// TODO: Find a faster way of doing this
None =>
List.append(tableItems, [(pathItem, TomlArray(arrItems))]),
}
Ok(TomlTable(tableItems))
},
_ => Err(TomlInvalidTableWrite),
}
},
_ => Err(TomlInvalidTableWrite),
}
},
[pathItem, ...rest] => {
match (rootTable) {
TomlTable(tableItems) => {
// Find Path Item
let pathItemIndex = List.findIndex(
((key, _)) => key == pathItem,
tableItems
)
if (rest == [] && !overWrite && pathItemIndex != None) {
Ok(TomlTable(tableItems))
} else {
let (tableKey, tableValue) = match (pathItemIndex) {
Some(pathItemIndex) => {
match (List.nth(pathItemIndex, tableItems)) {
Some(item) => item,
None => fail "Impossible5",
}
},
None => (pathItem, TomlTable([])),
}
match (
writeTable(
rest,
tableElement,
tableValue,
writeArray,
overWrite=overWrite
)
) {
Err(err) => Err(err),
Ok(item) => {
let tableItems = match (pathItemIndex) {
Some(pathItemIndex) => {
// TODO: Find a faster way todo this
let arr = Array.fromList(tableItems)
arr[pathItemIndex] = (pathItem, item)
Array.toList(arr)
},
// TODO: Find a faster way of doing this
None => List.append(tableItems, [(pathItem, item)]),
}
Ok(TomlTable(tableItems))
},
}
}
},
_ => Err(TomlInvalidTableWrite),
}
},
_ => Ok(tableElement),
}
}
let skipComment = parserState => {
let mut hasHitComment = false
let mut hasHitNewLine = false
while (!isAtEndOfInput(parserState)) {
match (parserState.currentCodePoint) {
// '#'
0x23 => hasHitComment = true,
// NewLine
c when isCurrentTokenNewLine(parserState) => {
hasHitNewLine = true
break
},
// Space
c when isCurrentTokenSpace(parserState) => void,
// Anything else
_ when !hasHitComment => break,
c => {
if (!isValidCommentChar(c)) {
return Err(
buildUnexpectedTokenError(
parserState,
"Unexpected Token In Comment: " ++ formatCodePointOrEOF(c)
),
)
}
},
}
next(parserState)
void
}
return Ok((hasHitComment, hasHitNewLine))
}
// A-Za-z0-9_-
let isValidBareKeyChar = c =>
c >= 0x41 && c <= 0x5A ||
c >= 0x61 && c <= 0x7A ||
c >= 0x30 && c <= 0x39 ||
c == 0x5F ||
c == 0x2D
// Parse
let rec parseKey = parserState => {
Buffer.clear(parserState.bufferParse)
let mut allowMore = true
let mut allowStop = false
let mut parsingBare = false
let mut key = []
let mut keyHasValue = false
while (!isAtEndOfInput(parserState)) {
match (parserState.currentCodePoint) {
// '
0x27 when allowMore && !parsingBare => {
let str = match (parseLitStringLiteral(parserState, false)) {
Ok(TomlString(str)) => str,
Err(err) => return Err(err),
_ => fail "Impossible7",
}
Buffer.clear(parserState.bufferParse)
Buffer.addString(str, parserState.bufferParse)
allowMore = false
allowStop = true
keyHasValue = true
},
// "
0x22 when allowMore && !parsingBare => {
let str = match (parseBasicStringLiteral(parserState, false)) {
Ok(TomlString(str)) => str,
Err(err) => return Err(err),
_ => fail "Impossible6",
}
Buffer.clear(parserState.bufferParse)
Buffer.addString(str, parserState.bufferParse)
allowMore = false
allowStop = true
keyHasValue = true
},
// .
0x2E => {
keyHasValue = false
parsingBare = false
if (!allowStop) {
let detail = "expected a A-Za-z0-9-_\"' digit, found ."
return Err(buildUnexpectedTokenError(parserState, detail))
}
next(parserState)
skipSpace(parserState)
allowMore = true
key = [Buffer.toString(parserState.bufferParse), ...key]
Buffer.clear(parserState.bufferParse)
allowStop = false
},
// Handle bare Key
c when isValidBareKeyChar(c) && allowMore => {
parsingBare = true
next(parserState)
addCharFromCodePoint(c, parserState.bufferParse)
allowStop = true
keyHasValue = true
},
// Handle Space
c when isCurrentTokenSpace(parserState) => {
next(parserState)
allowMore = false
},
// Invalid Key Value
c => break,
}
}
if (keyHasValue == true)
key = [Buffer.toString(parserState.bufferParse), ...key]
if (List.length(key) == 0 && Buffer.length(parserState.bufferParse) == 0) {
return Err(TomlInvalidKey)
}
// Return Key Path
return Ok(List.reverse(key))
}
// Parse Literal
and parseTrueLiteral = parserState => {
match (expectCodePointAndAdvance(0x74, parserState)) {
// 't'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x72, parserState)) {
// 'r'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x75, parserState)) {
// 'u'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x65, parserState)) {
// 'e'
Some(e) => Err(e),
None => Ok(TomlBool(true)),
}
},
}
},
}
},
}
}
and parseFalseLiteral = parserState => {
match (expectCodePointAndAdvance(0x66, parserState)) {
// 'f'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x61, parserState)) {
// 'a'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x6C, parserState)) {
// 'l'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x73, parserState)) {
// 's'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x65, parserState)) {
// 'e'
Some(e) => Err(e),
None => Ok(TomlBool(false)),
}
},
}
},
}
},
}
},
}
}
and parseNumberLiteral = parserState => {
let buffer = parserState.bufferParse
Buffer.clear(buffer)
// First char can optionally be a minus sign.
let mut c = parserState.currentCodePoint
let mut isFloat = false
let mut base = 10
let mut leadingZero = false
let isNegative = c == 0x2D
let hasLeadingPositive = c == 0x2B
// '-' || '+'
if (isNegative || hasLeadingPositive) {
c = next(parserState)
}
// Handle Parsing Numeric Half
// After that, the first/second char can only be a decimal digit ('0'..'9').
match (c) {
// nan
0x6E => { // 'n'
next(parserState)
let result = match (expectCodePointAndAdvance(0x61, parserState)) {
// 'a'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x6E, parserState)) {
// 'n'
Some(e) => Err(e),
None => Ok(TomlFloat(NaN)),
}
},
}
return result
},
// inf
0x69 => { // 'i'
next(parserState)
let result = match (expectCodePointAndAdvance(0x6E, parserState)) {
// 'n'
Some(e) => Err(e),
None => {
match (expectCodePointAndAdvance(0x66, parserState)) {
// 'f'
Some(e) => Err(e),
None => {
if (isNegative)
Ok(TomlFloat(Infinity * (if (isNegative) -1.0 else 1.0)))
else
Ok(TomlInt(Infinity))
},
}
},
}
return result
},
0x30 => { // '0'
// Toml doesn't allow numbers with additional leading zeros like
// "01". Which means that if a number starts with zero then the
// integer part is just zero and the next one can only be one of
// '.', 'e' or 'E'. In any case all that needs to be done here is
// to advance over the zero character and proceed to the optional
// fractional and exponential parts. If another digit follows then
// a parsing error will occur as expected, but implicitly because
// this function finishes with the parser positioned on a digit
// and not on a token expected after a number like ',', ']', '}' or
// EOF.
addCharFromCodePoint(c, buffer)
c = next(parserState)
leadingZero = true
},
x when x >= 0x31 && x <= 0x39 && base == 10 => { // '1'..'9'
let mut lastDigit = false
let mut allowUnderScore = false
for (;;) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
if (c != 0x5F) addCharFromCodePoint(c, buffer)
c = next(parserState)
if (c < 0x30 || c > 0x39 && c != 0x5F) {
break
}
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
void
},
unexpectedCodePoint => {
// The integer part of the number has to have at least one digit.
// JSON doesn't allow numbers starting with decimal separator like ".1".
let detail = "expected a decimal digit, found " ++
formatCodePointOrEOF(unexpectedCodePoint)
return Err(buildUnexpectedTokenError(parserState, detail))
},
}
// Handle Other Number Types
if (leadingZero && !isNegative && !hasLeadingPositive) {
match (c) {
0x78 => { // 'x'
Buffer.addChar('x', buffer)
base = 16
c = next(parserState)
let mut i = 0
let mut allowUnderScore = false
for (;
c >= 0x30 && c <= 0x39 ||
c >= 0x41 && c <= 0x46 ||
c >= 0x61 && c <= 0x66 ||
c == 0x5F;
i += 1
) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
addCharFromCodePoint(c, buffer)
c = next(parserState)
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
if (i == 0) {
let detail = "expected a hex digit, found " ++ formatCodePointOrEOF(c)
return Err(buildUnexpectedTokenError(parserState, detail))
}
},
0x6F => { // 'o'
Buffer.addChar('o', buffer)
base = 8
c = next(parserState)
let mut i = 0
let mut allowUnderScore = false
for (; c >= 0x30 && c <= 0x37 || c == 0x5F; i += 1) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
addCharFromCodePoint(c, buffer)
c = next(parserState)
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
if (i == 0) {
let detail = "expected an octal digit, found " ++
formatCodePointOrEOF(c)
return Err(buildUnexpectedTokenError(parserState, detail))
}
},
0x62 => { // 'b'
Buffer.addChar('b', buffer)
base = 2
c = next(parserState)
let mut i = 0
let mut allowUnderScore = false
for (; c >= 0x30 && c <= 0x31 || c == 0x5F; i += 1) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
addCharFromCodePoint(c, buffer)
c = next(parserState)
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
if (i == 0) {
let detail = "expected a binary digit, found " ++
formatCodePointOrEOF(c)
return Err(buildUnexpectedTokenError(parserState, detail))
}
},
_ => void,
}
}
// Optional fractional part of the number.
if (base == 10 && c == 0x2E) { // '.'
isFloat = true
Buffer.addChar('.', buffer)
c = next(parserState)
let mut i = 0
let mut allowUnderScore = false
for (; c >= 0x30 && c <= 0x39 || c == 0x5F; i += 1) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
if (c != 0x5F) addCharFromCodePoint(c, buffer)
c = next(parserState)
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
if (i == 0) {
let detail = "expected a decimal digit, found " ++ formatCodePointOrEOF(c)
return Err(buildUnexpectedTokenError(parserState, detail))
}
}
// Optional exponential part of the number.
if (base == 10 && c == 0x65 || c == 0x45) { // 'e' or 'E'
isFloat = true
Buffer.addChar('e', buffer)
c = next(parserState)
// can start with optional plus or minus sign
match (c) {
0x2D => { // '-'
c = next(parserState)
Buffer.addChar('-', buffer)
},
0x2B => { // '+'
c = next(parserState)
},
_ => void,
}
// followed by one or more digits (0-9)
let mut i = 0
let mut allowUnderScore = false
for (; c >= 0x30 && c <= 0x39 || c == 0x5F; i += 1) {
if (c == 0x5F) {
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
allowUnderScore = false
} else {
allowUnderScore = true
}
if (c != 0x5F) addCharFromCodePoint(c, buffer)
c = next(parserState)
}
if (!allowUnderScore) {
let detail = "unexpected '_' in number"
return Err(buildUnexpectedTokenError(parserState, detail))
}
if (i == 0) {
let detail = "expected a decimal digit, found " ++ formatCodePointOrEOF(c)
return Err(buildUnexpectedTokenError(parserState, detail))
}
void
}
// Note that unlike all other Toml value types there's no explicit ending
// character like ('"' for strings, ']' for arrays,'}' for objects etc). We
// just leave the parser state at current position and the reading of next
// token will succeed or fail, but number parsing just ends here.
return match (isFloat) {
false when base == 10 => {
let result = atoiFast(buffer)
Ok(TomlInt(if (isNegative) result * -1 else result))
},
false => {
let str = Buffer.toString(buffer)
match (Number.parseInt(str, base)) {
Err(err) => fail "Impossible1",
Ok(result) => {
Ok(TomlInt(if (isNegative) result * -1 else result))
},
}
},
true => {
let str = Buffer.toString(buffer)
match (Number.parseFloat(str)) {
Err(err) => fail "Impossible2",
Ok(result) => {
Ok(TomlFloat(if (isNegative) result * -1 else result))
},
}
},
}
}
// TODO: Consider Combining literal and basic string parsing to deduplicate code
and parseBasicStringLiteral = (parserState, allowMultiLine) => {
let strBuffer = parserState.bufferParse
Buffer.clear(strBuffer)
let mut hasHitContent = false
let mut isMultiLine = false
while (true) {
match (parserState.currentCodePoint) {
0x22 => { // '"'
// TODO: Clean Up All The Quote Logic Here And For Lit String
let mut quoteCount = 0
while (parserState.currentCodePoint == 0x22) {
next(parserState)
quoteCount += 1
}
if (quoteCount > 6 || quoteCount == 6 && hasHitContent) {
return Err(UnexpectedEndOfString)
} else if (quoteCount == 2 && !hasHitContent) {
break
} else if (quoteCount == 6 && !hasHitContent) {
break
} else if (quoteCount == 1) {
if (isMultiLine) {
Buffer.addChar('"', strBuffer)
} else {
if (hasHitContent) break
}
} else if (quoteCount >= 3) {
if (!allowMultiLine) {
return Err(
buildUnexpectedTokenError(
parserState,
"Multi-line string literal not allowed here"
),
)
}
for (let mut i = 3; i < quoteCount; i += 1) {
Buffer.addChar('"', strBuffer)
}
if (hasHitContent) break else isMultiLine = true
} else {
for (let mut i = 0; i < quoteCount; i += 1) {
Buffer.addChar('"', strBuffer)
}
}
},
// Escape Chars
0x5C => { // '\'
hasHitContent = true
next(parserState)
match (parserState.currentCodePoint) {
0x62 => { // 'b'
next(parserState)
Buffer.addChar('\u0008', strBuffer) // BackSpace
},
0x74 => { // 't'
next(parserState)
Buffer.addChar('\u0009', strBuffer) // Tab
},
0x6E => { // 'n'
next(parserState)
Buffer.addChar('\u000A', strBuffer) // LineFeed
},
0x66 => { // 'f'