forked from grain-lang/grain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.gr
2084 lines (1937 loc) · 61.4 KB
/
json.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
/**
* JSON (JavaScript Object Notation) parsing, printing, and access utilities.
*
* @example from "json" include Json
* @example Json.parse("{\"currency\":\"€\",\"price\":99.99}")
* @example
* print(
* toString(
* format=Pretty,
* JsonObject([("currency", JsonString("€")), ("price", JsonNumber(99.9))])
* )
* )
*/
module Json
from "runtime/bigint" include Bigint as BI
from "runtime/dataStructures" include DataStructures
from "runtime/numbers" include Numbers
from "runtime/numberUtils" include NumberUtils
from "runtime/string" include String as RuntimeString
from "runtime/unsafe/tags" include Tags
from "runtime/unsafe/wasmi32" include WasmI32
from "runtime/unsafe/wasmi64" include WasmI64
from "runtime/unsafe/wasmf64" include WasmF64
from "runtime/atof/parse" include Parse as Atof
from "buffer" include Buffer
from "char" include Char
from "string" include String
from "list" include List
from "uint8" include Uint8
use RuntimeString.{ toString as runtimeToString, getCodePoint }
use Numbers.{ coerceNumberToWasmI32 }
use DataStructures.{ tagSimpleNumber, untagSimpleNumber }
// Primitive offsets
// TODO(#703): Get these offsets from the runtime
@unsafe
let _INT64_BOXED_VALUE_OFFSET = 8n
@unsafe
let _Float64_BOXED_VALUE_OFFSET = 8n
/**
* Data structure representing JSON in Grain.
*
* @example
* assert Json.parse("{\"currency\":\"€\",\"price\":99.99}") == JsonObject([
* ("currency", JsonString("€")),
* ("price", JsonNumber(99.99)),
* ])
*
* @example
* assert Json.parse("{\n\"currency\":\"€\",\n\"price\":99.99\n}") == JsonObject([
* ("currency", JsonString("€")),
* ("price", JsonNumber(99.99)),
* ])
*/
provide enum rec Json {
JsonNull,
JsonBoolean(Bool),
JsonNumber(Number),
JsonString(String),
JsonArray(List<Json>),
// Note that JsonObject here is deliberately defined as a simple list of key value pair tuples as opposed
// to for example a Map in order to accommodate the fact that the ECMA-404 standard doesn't prohibit
// duplicate names in Objects. Such JSON should be representable by the JSON data structure for lossless
// processing. This also simplifies implementation by not requiring a purpose built data structure and
// has the benefit of List's immutability. It's a conscious decision that sacrifices ease of use of the
// API for lossless handing of these edge cases with intention of later building more ergonomic APIs on a
// higher level of abstraction.
JsonObject(List<(String, Json)>),
}
/**
* Represents errors for cases where a `Json` data structure cannot be represented as a
* JSON string.
*/
provide enum JsonToStringError {
/**
* The `Json` data structure contains a number value of `NaN`, `Infinity`, or `-Infinity`.
*/
InvalidNumber(String),
}
/**
* Controls how indentation is output in custom formatting.
*/
provide enum IndentationFormat {
/**
* No indentation is emitted.
*
* ```json
* {
* "currency": "€",
* "price": 99.9
* }
* ```
*/
NoIndentation,
/**
* Tabs are emitted.
*
* ```json
* {
* "currency": "€",
* "price": 99.9
* }
* ```
*/
IndentWithTab,
/**
* The desired number of spaces are emitted.
*
* `IndentWithSpaces(2)`
* ```json
* {
* "currency": "€",
* "price": 99.9
* }
* ```
*
* `IndentWithSpaces(4)`
* ```json
* {
* "currency": "€",
* "price": 99.9
* }
* ```
*/
IndentWithSpaces(Number),
}
/**
* Controls how arrays are output in custom formatting.
*/
provide enum ArrayFormat {
/**
* Arrays are emitted in a compact manner.
*
* ```json
* []
* ```
*
* ```json
* [1]
* ```
*
* ```json
* [1,2,3]
* ```
*/
CompactArrayEntries,
/**
* Arrays are emitted with spaces between elements.
*
* ```json
* [ ]
* ```
*
* ```json
* [1]
* ```
*
* ```json
* [1, 2, 3]
* ```
*/
SpacedArrayEntries,
/**
* Arrays are emitted with newlines and indentation between each element.
*
* ```json
* []
* ```
*
* ```json
* [
* 1
* ]
* ```
*
* ```json
* [
* 1,
* 2,
* 3
* ]
* ```
*/
OneArrayEntryPerLine,
}
/**
* Controls how objects are output in custom formatting.
*/
provide enum ObjectFormat {
/**
* Objects are emitted in a compact manner.
*
* ```json
* {}
* ```
*
* ```json
* {"a":1}
* ```
*
* ```json
* {"a":1,"b":2,"c":3}
* ```
*/
CompactObjectEntries,
/**
* Objects are emitted with spaces between entries.
*
* ```json
* { }
* ```
*
* ```json
* {"a": 1}
* ```
*
* ```json
* {"a": 1, "b": 2, "c": 3}
* ```
*/
SpacedObjectEntries,
/**
* Objects are emitted with each entry on a new line.
*
* ```
* {}
* ```
*
* ```
* {
* "a": 1
* }
* ```
*
* ```
* {
* "a": 1,
* "b": 2,
* "c": 3
* }
* ```
*/
OneObjectEntryPerLine,
}
/**
* Controls how line endings are output in custom formatting.
*/
provide enum LineEnding {
/**
* No line endings will be emitted.
*/
NoLineEnding,
/**
* A `\n` will be emitted at the end of each line.
*/
LineFeed,
/**
* A `\r\n` will be emitted at the end of each line.
*/
CarriageReturnLineFeed,
/**
* A `\r` will be emitted at the end of each line.
*/
CarriageReturn,
}
/*
* Allows fine-grained control of formatting in JSON output.
*/
record FormattingSettings {
indentation: IndentationFormat,
arrayFormat: ArrayFormat,
objectFormat: ObjectFormat,
lineEnding: LineEnding,
finishWithNewLine: Bool,
escapeAllControlPoints: Bool,
escapeHTMLUnsafeSequences: Bool,
escapeNonASCII: Bool,
}
/**
* Allows control of formatting in JSON output.
*/
provide enum FormattingChoices {
/**
* Recommended human readable formatting.
*
* Escapes all control points for the sake of clarity, but outputs unicode
* codepoints directly so the result needs to be treated as proper unicode and
* is not safe to be transported in ASCII encoding.
*
* Roughly Equivalent to:
* ```grain
* Custom{
* indentation: IndentWithSpaces(2),
* arrayFormat: OneArrayEntryPerLine,
* objectFormat: OneObjectEntryPerLine,
* lineEnding: LineFeed,
* finishWithNewLine: true,
* escapeAllControlPoints: true,
* escapeHTMLUnsafeSequences: false,
* escapeNonASCII: false,
* }
* ```
*
* ```json
* {
* "currency": "€",
* "price": 99.9,
* "currencyDescription": "EURO\u007f",
* }
* ```
*/
Pretty,
/**
* Compact formatting that minimizes the size of resulting JSON at cost of not
* being easily human readable.
*
* Only performs minimal string escaping as required by the ECMA-404 standard,
* so the result needs to be treated as proper unicode and is not safe to be
* transported in ASCII encoding.
*
* Roughly Equivalent to:
* ```grain
* Custom{
* indentation: NoIndentation,
* arrayFormat: CompactArrayEntries,
* objectFormat: CompactObjectEntries,
* lineEnding: NoLineEnding,
* finishWithNewLine: false,
* escapeAllControlPoints: false,
* escapeHTMLUnsafeSequences: false,
* escapeNonASCII: false,
* }
* ```
*
* ```json
* {"currency":"€","price":99.9,"currencyDescription":"EURO␡"}
* ```
*/
Compact,
/**
* Pretty and conservative formatting to maximize compatibility and
* embeddability of the resulting JSON.
*
* Should be safe to copy and paste directly into HTML and to be transported in
* plain ASCII.
*
* Roughly Equivalent to:
* ```grain
* Custom{
* indentation: IndentWithSpaces(2),
* arrayFormat: OneArrayEntryPerLine,
* objectFormat: OneObjectEntryPerLine,
* lineEnding: LineFeed,
* finishWithNewLine: true,
* escapeAllControlPoints: true,
* escapeHTMLUnsafeSequences: true,
* escapeNonASCII: true,
* }
* ```
*
* ```json
* {
* "currency": "\u20ac",
* "price": 99.9,
* "currencyDescription": "EURO\u007f",
* }
* ```
*/
PrettyAndSafe,
/**
* Compact and conservative formatting to maximize compatibility and
* embeddability of the resulting JSON.
*
* Should be safe to copy and paste directly into HTML and to transported in
* plain ASCII.
*
* Roughly Equivalent to:
* ```grain
* Custom{
* indentation: NoIndentation,
* arrayFormat: CompactArrayEntries,
* objectFormat: CompactObjectEntries,
* lineEnding: NoLineEnding,
* finishWithNewLine: false,
* escapeAllControlPoints: true,
* escapeHTMLUnsafeSequences: true,
* escapeNonASCII: true,
* }
* ```
*
* ```json
* {"currency":"\u20ac","price":99.9,"currencyDescription":"EURO\u007f"}
* ```
*/
CompactAndSafe,
/**
* Allows for fined grained control of the formatting output.
*/
Custom{
indentation: IndentationFormat,
arrayFormat: ArrayFormat,
objectFormat: ObjectFormat,
lineEnding: LineEnding,
finishWithNewLine: Bool,
escapeAllControlPoints: Bool,
escapeHTMLUnsafeSequences: Bool,
escapeNonASCII: Bool,
},
}
record JsonWriterConfig {
format: FormattingSettings,
buffer: Buffer.Buffer,
emitEscapedQuotedString: String => Void,
printNewLine: Option<() => Void>,
printIndentation: Option<Number => Void>,
}
// The idea for this type is to allow reusing a bit of work done in preparing for printing JSON.
// For now this is not exposed and remains an internal implementation detail.
// It may make sense in the future to expose it and let the user reuse a writer for multiple
// JSON emit operations without reallocating new closures and buffers each time.
record JsonWriter {
emit: Json => Option<JsonToStringError>,
}
let emitUTF16EscapeSequence = (codePoint: Number, buffer: Buffer.Buffer) => {
// Emit the "\u" followed by hexadecimal representation of the codepoint
// with fixed length of 4 hexadecimal digits corresponding to the two byte
// codepoint. No checks are performed here if the codepoint is in the
// "Basic Multilingual Plane" (0000-FFFF) as this function is only called
// internally.
// An alternative was to this implementation was to use NumberUtils.itoa32,
// but this avoids unnecessary heap allocations. As a possible future
// optimization this loop could be unrolled possibly even converted to be
// branchless and SIMD optimized, but it could be a bit of an overkill as
// this codepath is only for escape sequences, which probably aren't all
// that common occurrence.
Buffer.addChar('\\', buffer)
Buffer.addChar('u', buffer)
// Loop over the four digit from most to least significant.
for (let mut digitIndex = 3; digitIndex >= 0; digitIndex -= 1) {
// Use bit masking and shifting to extract from the codepoint a number
// with just the bits corresponding to this hexadecimal digit.
let shift = digitIndex * 4
let mask = 0b1111 << shift
let digit = (codePoint & mask) >>> shift
// Digit now is a number in the range 0..15 and we need to translate it
// into a unicode codepoint representing the hexadecimal digit
// (0..9/a..f). We can use the fact that digits and latin letters in
// ASCII and by extension in Unicode are adjacent and ordered.
let hexDigitCodePoint = if (digit <= 9) {
// 48 is codepoint for char '0'
digit + 48
} else {
// 97 is codepoint for char 'a'
// But we also need to subtract 10 from it because we need
// the 10..15 number range translated to 0..5 in order to
// serve as an index in the ASCI range 'a'..'f'.
digit + 87
}
Buffer.addCharFromCodePoint(hexDigitCodePoint, buffer)
}
}
let emitEscapedUnicodeSequence = (codePoint: Number, buffer: Buffer.Buffer) => {
// See the String section in the ECMA-404 doc.
// If the code point is "in the Basic Multilingual Plane", that is in range
// 0..65535. Greater values need to be split into two UTF-16 chunks.
if (codePoint <= 0xFFFF) {
emitUTF16EscapeSequence(codePoint, buffer)
} else {
// The following three lines are copied from String module of Grain's
// stdlib. It would be nice to share more code. On the other hand it
// may make sense to just have these few instructions directly here
// from the performance standpoint so we can print millions of emojis
// per second 😄.
// https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF
let uPrime = codePoint - 0x10000
let highSurrogate = ((uPrime & 0b11111111110000000000) >>> 10) + 0xD800
// High surrogate
let lowSurrogate = (uPrime & 0b00000000001111111111) + 0xDC00
// Low surrogate
emitUTF16EscapeSequence(highSurrogate, buffer)
emitUTF16EscapeSequence(lowSurrogate, buffer)
}
}
let emitEscapedCodePoint = (codePoint: Number, buffer: Buffer.Buffer) => {
match (codePoint) {
0x0008 => { // backspace
Buffer.addChar('\\', buffer)
Buffer.addChar('b', buffer)
},
0x0009 => { // tab
Buffer.addChar('\\', buffer)
Buffer.addChar('t', buffer)
},
0x000A => { // line feed
Buffer.addChar('\\', buffer)
Buffer.addChar('n', buffer)
},
0x000C => { // form feed
Buffer.addChar('\\', buffer)
Buffer.addChar('f', buffer)
},
0x000D => { // carriage return
Buffer.addChar('\\', buffer)
Buffer.addChar('r', buffer)
},
0x0022 => { // quotation mark
Buffer.addChar('\\', buffer)
Buffer.addChar('"', buffer)
},
0x005C => { // backslash or "Reverse Solidus"
Buffer.addChar('\\', buffer)
Buffer.addChar('\\', buffer)
},
_ => {
emitEscapedUnicodeSequence(codePoint, buffer)
},
}
}
let printNull = (buffer: Buffer.Buffer) => Buffer.addString("null", buffer)
let printBool = (b: Bool, buffer: Buffer.Buffer) => {
if (b) {
Buffer.addString("true", buffer)
} else {
Buffer.addString("false", buffer)
}
}
@unsafe
let printNumberWasmI32 = (value: WasmI32, buffer: Buffer.Buffer) => {
let s = NumberUtils.itoa32(value, 10n)
Buffer.addString(s, buffer)
}
@unsafe
let printNumberWasmI64 = (value: WasmI64, buffer: Buffer.Buffer) => {
let s = NumberUtils.itoa64(value, 10n)
Buffer.addString(s, buffer)
}
@unsafe
let isFinite = (value: WasmF64) => {
use WasmF64.{ (==), (-) }
value - value == 0.0W
}
@unsafe
let isNaN = (value: WasmF64) => {
use WasmF64.{ (!=) }
value != value
}
@unsafe
let printNumberWasmF64 = (value: WasmF64, buffer: Buffer.Buffer) => {
if (isFinite(value)) {
let s = NumberUtils.dtoa(value)
Buffer.addString(s, buffer)
None
} else {
use WasmF64.{ (<) }
// JSON standard doesn't allow NaN or infinite values in numbers,
// but WASM f64 (IEEE 754-2008), as well as Grain's number types do
// (Float64 as well as Number). This is the only reason that the
// formatting needs to return a Result and not just a String
// directly. Other possible choices were to throw exceptions or to
// continue formatting without representing these values correctly
// (like JavaScript's JSON.stringify).
if (isNaN(value)) {
Some(InvalidNumber("NaN is not allowed in JsonNumber"))
} else if (value < 0.0W) {
Some(InvalidNumber("-Infinity is not allowed in JsonNumber"))
} else {
Some(InvalidNumber("Infinity is not allowed in JsonNumber"))
}
}
}
@unsafe
let printNumber = (value: Number, buffer: Buffer.Buffer) => {
use WasmI32.{ (&), (==), (!=), (<<), (>>) }
let ptr = WasmI32.fromGrain(value)
let ret = if ((ptr & 1n) != 0n) {
printNumberWasmI32(untagSimpleNumber(value), buffer)
None
} else if ((ptr & 7n) == Tags._GRAIN_GENERIC_HEAP_TAG_TYPE) {
let tag = WasmI32.load(ptr, 0n)
match (tag) {
t when t == Tags._GRAIN_BOXED_NUM_HEAP_TAG => {
let numberTag = WasmI32.load(ptr, 4n)
match (numberTag) {
t when t == Tags._GRAIN_INT64_BOXED_NUM_TAG => {
let asWasmI64 = WasmI64.load(ptr, _INT64_BOXED_VALUE_OFFSET)
printNumberWasmI64(asWasmI64, buffer)
None
},
t when t == Tags._GRAIN_BIGINT_BOXED_NUM_TAG => {
Buffer.addString(BI.bigIntToString10(ptr), buffer)
None
},
t when t == Tags._GRAIN_RATIONAL_BOXED_NUM_TAG => {
// JSON does not support rationals as a compromise
// we coerce them to an f64 and print that
// this means there is a slight loss in precision
let asFloat64 = Numbers.coerceNumberToFloat64(value)
let ptr = WasmI32.fromGrain(asFloat64)
let asWasmF64 = WasmF64.load(ptr, _Float64_BOXED_VALUE_OFFSET)
printNumberWasmF64(asWasmF64, buffer)
},
t when t == Tags._GRAIN_FLOAT64_BOXED_NUM_TAG => {
let asWasmF64 = WasmF64.load(ptr, _Float64_BOXED_VALUE_OFFSET)
printNumberWasmF64(asWasmF64, buffer)
},
_ => {
fail "Impossible: Json.toString encountered an unknown number tag"
},
}
},
_ => {
fail "Impossible: Json.toString encountered an unknown number tag"
},
}
} else {
fail "Impossible: Json.toString encountered an unknown number tag"
}
// This keeps the gc from prematurely freeing the value
ignore(value)
ret
}
// Note that this compromises on peak performance by also handling
// the compact printing case, merging these two together greatly simplifies the amount
// of code we need to maintain so it seems worth it.
let rec printElement = (
json: Json,
implHelper: JsonWriterConfig,
indentationLevel: Number,
) => {
let buffer = implHelper.buffer
match (json) {
JsonNull => {
printNull(buffer)
return None
},
JsonBoolean(b) => {
printBool(b, buffer)
return None
},
JsonNumber(n) => return printNumber(n, buffer),
JsonString(s) => {
implHelper.emitEscapedQuotedString(s)
return None
},
JsonArray(elems) => {
match (elems) {
[] => {
Buffer.addChar('[', buffer)
if (implHelper.format.arrayFormat == SpacedArrayEntries) {
Buffer.addChar(' ', buffer)
}
Buffer.addChar(']', buffer)
return None
},
[e] => {
let format = implHelper.format
Buffer.addChar('[', buffer)
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
}
let elemLevel = indentationLevel + 1
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(elemLevel),
None => void,
}
}
match (printElement(e, implHelper, elemLevel)) {
None => void,
err => return err,
}
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(indentationLevel),
None => void,
}
}
Buffer.addChar(']', buffer)
return None
},
[initialHead, ...initialRest] => {
let format = implHelper.format
Buffer.addChar('[', buffer)
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
}
let mut currentHead = initialHead
let mut currentRest = initialRest
let elemLevel = indentationLevel + 1
for (let mut index = 0;; index += 1) {
if (index > 0) {
Buffer.addChar(',', buffer)
if (format.arrayFormat == SpacedArrayEntries) {
Buffer.addChar(' ', buffer)
}
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
}
}
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(elemLevel),
None => void,
}
}
match (printElement(currentHead, implHelper, elemLevel)) {
None => void,
err => return err,
}
match (currentRest) {
[] => break,
[newHead, ...newRest] => {
currentHead = newHead
currentRest = newRest
},
}
}
if (format.arrayFormat == OneArrayEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(indentationLevel),
None => void,
}
}
Buffer.addChar(']', buffer)
return None
},
}
},
JsonObject(entries) => {
match (entries) {
[] => {
Buffer.addChar('{', buffer)
if (implHelper.format.objectFormat == SpacedObjectEntries) {
Buffer.addChar(' ', buffer)
}
Buffer.addChar('}', buffer)
return None
},
[(key, value)] => {
let format = implHelper.format
Buffer.addChar('{', buffer)
let elemLevel = indentationLevel + 1
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(elemLevel),
None => void,
}
}
implHelper.emitEscapedQuotedString(key)
Buffer.addChar(':', buffer)
match (format.objectFormat) {
CompactObjectEntries => void,
SpacedObjectEntries | OneObjectEntryPerLine => {
Buffer.addChar(' ', buffer)
},
}
match (printElement(value, implHelper, elemLevel)) {
None => void,
err => return err,
}
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(indentationLevel),
None => void,
}
}
Buffer.addChar('}', buffer)
return None
},
[initialHead, ...initialRest] => {
let format = implHelper.format
Buffer.addChar('{', buffer)
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
}
let mut currentHead = initialHead
let mut currentRest = initialRest
let elemLevel = indentationLevel + 1
for (let mut index = 0;; index += 1) {
if (index > 0) {
Buffer.addChar(',', buffer)
if (format.objectFormat == SpacedObjectEntries) {
Buffer.addChar(' ', buffer)
}
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
}
}
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(elemLevel),
None => void,
}
}
let (key, value) = currentHead
implHelper.emitEscapedQuotedString(key)
Buffer.addChar(':', buffer)
match (format.objectFormat) {
CompactObjectEntries => void,
SpacedObjectEntries | OneObjectEntryPerLine => {
Buffer.addChar(' ', buffer)
},
}
match (printElement(value, implHelper, elemLevel)) {
None => void,
err => return err,
}
match (currentRest) {
[] => break,
[newHead, ...newRest] => {
currentHead = newHead
currentRest = newRest
},
}
}
if (format.objectFormat == OneObjectEntryPerLine) {
match (implHelper.printNewLine) {
Some(printNewLine) => printNewLine(),
None => void,
}
match (implHelper.printIndentation) {
Some(printIndentation) => printIndentation(indentationLevel),
None => void,
}
}
Buffer.addChar('}', buffer)
return None
},
}
},
}
}
let isCodePointInBasicMultilingualPlane = (code: Number) =>
code >= 0x0000 && code <= 0xFFFF
let isHighSurrogate = (code: Number) => code >= 0xD800 && code <= 0xDBFF
let isLowSurrogate = (code: Number) => code >= 0xDC00 && code <= 0xDFFF
let combineSurrogatePairToCodePoint = (
highSurrogate: Number,
lowSurrogate: Number,
) => {
// If this was a method exposed by itself in a library then it should check the
// ranges of the input surrogates, but here it's necessary because checks are made
// as part of the parsing logic.
((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000
}
let makeJsonWriter = (format: FormattingSettings, buffer: Buffer.Buffer) => {
let printNewLine = match (format.lineEnding) {
NoLineEnding => None,
LineFeed => Some(() => {
Buffer.addChar('\n', buffer)
}),
CarriageReturnLineFeed => Some(() => {
Buffer.addChar('\r', buffer)
Buffer.addChar('\n', buffer)
}),
CarriageReturn => Some(() => {
Buffer.addChar('\r', buffer)
}),
}
let printIndentation = match (format.indentation) {
IndentWithTab => Some(indentationLevel => {
for (let mut count = 0; count < indentationLevel; count += 1) {
Buffer.addChar('\t', buffer)
}
}),
// Implement fast path, for common indentation level to avoid closure
IndentWithSpaces(spacesPerIndentation) when spacesPerIndentation == 2 =>
Some(indentationLevel => {
let spaceCount = indentationLevel * 2
for (let mut count = 0; count < spaceCount; count += 1) {
Buffer.addChar(' ', buffer)
}
}),
// Implement fast path, for common indentation level to avoid closure
IndentWithSpaces(spacesPerIndentation) when spacesPerIndentation == 4 =>
Some(indentationLevel => {
let spaceCount = indentationLevel * 4
for (let mut count = 0; count < spaceCount; count += 1) {
Buffer.addChar(' ', buffer)
}
}),
IndentWithSpaces(spacesPerIndentation) => Some(indentationLevel => {
let spaceCount = indentationLevel * spacesPerIndentation
for (let mut count = 0; count < spaceCount; count += 1) {
Buffer.addChar(' ', buffer)
}
}),
NoIndentation => None,
}