-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.gr
2186 lines (1950 loc) · 64.9 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
/**
* @module Json: JSON (JavaScript Object Notation) parsing and printing.
*/
import String from "string"
import Char from "char"
import List from "list"
import Option from "option"
import Number from "number"
import WasmI32 from "runtime/unsafe/wasmi32"
import WasmI64 from "runtime/unsafe/wasmi64"
import WasmF32 from "runtime/unsafe/wasmf32"
import WasmF64 from "runtime/unsafe/wasmf64"
import NumberUtils from "runtime/numberUtils"
import Tags from "runtime/unsafe/tags"
import Numbers from "runtime/numbers"
import Memory from "runtime/unsafe/memory"
import StringReader from "./stringreader"
import Buffer from "buffer"
import { toString as runtimeToString } from "runtime/string"
import { coerceNumberToWasmI32 } from "runtime/numbers"
/**
* Data structure representing the result of parsing and the input of printing
* JSON.
*
* For example this object
* ```grain
* JSONObject([
* ("currency", JSONString("€")),
* ("price", JSONNumber(99.99)),
* ])
* ```
* is equivalent to the following JSON:
* ```json
* {"currency":"€","price":99.99}
* ```
*
* This data structure is semantically equivalent to the JSON format allowing
* mostly lossless round trips of printing and parsing. Exceptions to this are
* white spaces, multiple ways JSON allows escaping characters in strings and
* some edge-cases related to Grain's `Number` type.
*
* For example parsing the following JSON text will also result in the same
* `JSON` object as above.
* ```json
* {
* "currency": "\u20ac",
* "price": 99.99
* }
* ```
*/
export enum JSON {
JSONNull,
JSONBoolean(Bool),
JSONNumber(Number),
JSONString(String),
// Here I've chosen to use a List and not an array as a conscious trade of performance for immutability.
// I'd love to use a more advanced persistent collection instead, but there currently aren't any in Grain.
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 accomodate 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 vastly simplifies implementation and has the benefit of List's immutability.
JSONObject(List<(String, JSON)>),
}
/**
* Represents errors for cases when a `JSON` object cannot be represente in the
* JSON format along with a human readable text message. This can happen when
* it contains number values `NaN`, `Infinity` or `-Infinity`.
*/
export enum JSONToStringError {
InvalidNumber(String),
}
/**
* Controls how indentation is performed in custom formatting.
*
* Following examples have whitespaces and line breaks replaced with visible
* charactes for illustrative purposes.
*
* `NoIndentation`
* ```
* {↵
* "currency":·"€",↵
* "price":·99.9↵
* }
* ```
*
* `IndentWithTab`
* ```
* {↵
* →"currency":·"€",↵
* →"price":·99.9↵
* }
* ```
*
* `IndentWithSpaces(2)`
* ```
* {↵
* ··"currency":·"€",↵
* ··"price":·99.9↵
* }
* ```
*
* `IndentWithSpaces(4)`
* ```
* {↵
* ····"currency":·"€",↵
* ····"price":·99.9↵
* }
* ```
*/
export enum IndentationFormat {
NoIndentation,
IndentWithTab,
IndentWithSpaces(Number),
}
/**
* Controls how arrays are printed in custom formatting.
*
* Following examples have whitespaces and line breaks replaced with visible
* charactes for illustrative purposes.
*
* `CompactArrayEntries`
* ```
* []
* ```
*
* ```
* [1]
* ```
*
* ```
* [1,2,3]
* ```
*
* `OneArrayEntryPerLine`
* ```
* []
* ```
*
* ```
* [↵
* ··1↵
* ]
* ```
*
* ```
* [↵
* ··1,↵
* ··2,↵
* ··3↵
* ]
* ```
*/
export enum ArrayFormat {
CompactArrayEntries,
OneArrayEntryPerLine,
}
/**
* Controls how objects are printed in custom formatting.
*
* Following examples have whitespaces and line breaks replaced with visible
* charactes for illustrative purposes.
*
* `CompactObjectEntries`
* ```
* {}
* ```
*
* ```
* {"a":1}
* ```
*
* ```
* {"a":1,"b":2,"c":3}
* ```
*
* `OneObjectEntryPerLine`
* ```
* {}
* ```
*
* ```
* {↵
* ··"a":·1↵
* }
* ```
*
* ```
* {↵
* ··"a":·1,↵
* ··"b":·2,↵
* ··"c":·3↵
* }
* ```
*/
export enum ObjectFormat {
CompactObjectEntries,
OneObjectEntryPerLine,
}
/**
* Controls line ending type in custom formatting.
*/
export enum LineEnding {
NoLineEnding,
LineFeed,
CarriageReturnLineFeed,
CarriageReturn,
}
/**
* Allows fine grained control of formatting in JSON printing.
*/
export record FormattingSettings {
indentation: IndentationFormat,
arrayFormat: ArrayFormat,
objectFormat: ObjectFormat,
lineEnding: LineEnding,
finishWithNewLine: Bool,
escapeAllControlPoints: Bool,
escapeHTMLUnsafeSequences: Bool,
escapeNonASCII: Bool,
}
/**
* 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.
*
* The following example have whitespaces, line breaks and control points
* replaced with visible characters.
* ```
* {"currency":"€","price":99.9,"currencyDescription":"EURO␡","script·unembeddable":"You·cannot·pase·a·JSON·object·directly·into·a·<script>·tag·in·HTML·if·it·contains·</·with·unescaped·forward·slash"}
* ```
*/
export let defaultCompactFormat = () =>
{
indentation: NoIndentation,
arrayFormat: CompactArrayEntries,
objectFormat: CompactObjectEntries,
lineEnding: NoLineEnding,
finishWithNewLine: false,
escapeAllControlPoints: false,
escapeHTMLUnsafeSequences: false,
escapeNonASCII: false,
}: FormattingSettings
/**
* Recommended human readable formatting.
*
* Escapes all control points for the sake of clarity, but prints unicode
* codepoints directly so the result needs to be treated as proper unicode and
* is not safe to be transported in ASCII encoding.
*
* The following example have whitespaces, line breaks and control points
* replaced with visible characters.
* ```
* {↵
* ··"currency":·"€",↵
* ··"price":·99.9,↵
* ··"currencyDescription":·"EURO\u007f",↵
* ··"script·unembeddable":·"You·cannot·pase·a·JSON·object·directly·into·a·<script>·tag·in·HTML·if·it·contains·</·with·unescaped·forward·slash"↵
* }
* ```
*/
export let defaultPrettyFormat = () =>
{
indentation: IndentWithSpaces(2),
arrayFormat: OneArrayEntryPerLine,
objectFormat: OneObjectEntryPerLine,
lineEnding: LineFeed,
finishWithNewLine: true,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: false,
escapeNonASCII: false,
}: FormattingSettings
/**
* 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.
*
* The following example have whitespaces, line breaks and control points
* replaced with visible characters.
* ```
* {"currency":"\u20ac","price":99.9,"currencyDescription":"EURO\u007f","script·unembeddable":"You·cannot·pase·a·JSON·object·directly·into·a·<script>·tag·in·HTML·if·it·contains·<\/·with·unescaped·forward·slash"}
* ```
*/
export let defaultCompactAndSafeFormat = () =>
{
indentation: NoIndentation,
arrayFormat: CompactArrayEntries,
objectFormat: CompactObjectEntries,
lineEnding: NoLineEnding,
finishWithNewLine: false,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: true,
escapeNonASCII: true,
}: FormattingSettings
/**
* 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 transported in
* plain ASCII.
*
* The following example have whitespaces, line breaks and control points
* replaced with visible characters.
* ```
* {↵
* ··"currency":·"\u20ac",↵
* ··"price":·99.9,↵
* ··"currencyDescription":·"EURO\u007f",↵
* ··"script·unembeddable":·"You·cannot·pase·a·JSON·object·directly·into·a·<script>·tag·in·HTML·if·it·contains·<\/·with·unescaped·forward·slash"↵
* }
* ```
*/
export let defaultPrettyAndSafeFormat = () =>
{
indentation: IndentWithSpaces(2),
arrayFormat: OneArrayEntryPerLine,
objectFormat: OneObjectEntryPerLine,
lineEnding: LineFeed,
finishWithNewLine: true,
escapeAllControlPoints: true,
escapeHTMLUnsafeSequences: true,
escapeNonASCII: true,
}: FormattingSettings
record JSONWriterCompactImplHelper {
buffer: Buffer.Buffer,
emitEscapedQuotedString: String -> Void,
}
record JSONWriterPrettyImplHelper {
format: FormattingSettings,
// Note that the "Pretty" suffix here is a workaround for a Grain compiler bug.
// It generates warnings just because two record types have some field names in common.
// Unless there's something I don't understand about its type system.
bufferPretty: Buffer.Buffer,
emitEscapedQuotedStringPretty: String -> Void,
printNewLine: () -> Void,
printIndentation: 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 addCharFromCodePoint = (codePoint: Number, buffer: Buffer.Buffer) => {
Buffer.addChar(Char.fromCode(codePoint), buffer)
}
let emitUTF16EscapeSequence = (codePoint: Number, buffer: Buffer.Buffer) => {
// Emit the "\u" followed by hexadecimal representation of the codepoint
// with fixed length of 4 hexadecimal digits correspondeing to the two byte
// codepoint. No checks are performed here if the codepoint is in the
// "Basic Multilingual Plane" (0000-FFFF) as this funcion is only called
// internally.
// An alternative was to this implementation was to use NumberUtils.itoa32,
// but I wanted to avoid 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 occurence.
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 hexadecinak 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 hexacedimal 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 codeppoint for char '0'
digit + 48
} else {
// 97 is codeppoint 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
}
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, writer)
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)
}
}
exception UnknownNumberTag
// The following few functions are only meant to be called from a @disableGC
// context of the printNumber function so there's no need to do all the
// reference adjustment for the parameters and the functions themselves.
@disableGC
let printNumberWasmI32 = (value: WasmI32, buffer: Buffer.Buffer) => {
let s = NumberUtils.itoa32(value, 10n)
Memory.incRef(WasmI32.fromGrain(Buffer.addString))
Memory.incRef(WasmI32.fromGrain(s))
Memory.incRef(WasmI32.fromGrain(buffer))
Buffer.addString(s, buffer)
Memory.decRef(WasmI32.fromGrain(s))
let none = None
Memory.incRef(WasmI32.fromGrain(none))
none
}
@disableGC
let printNumberWasmI64 = (value: WasmI64, buffer: Buffer.Buffer) => {
let s = NumberUtils.itoa64(value, 10n)
Memory.incRef(WasmI32.fromGrain(Buffer.addString))
Memory.incRef(WasmI32.fromGrain(s))
Memory.incRef(WasmI32.fromGrain(buffer))
Buffer.addString(s, buffer)
Memory.decRef(WasmI32.fromGrain(s))
let none = None
Memory.incRef(WasmI32.fromGrain(none))
none
}
@disableGC
let isFinite = (value: WasmF64) => {
WasmF64.eq(WasmF64.sub(value, value), 0.W)
}
@disableGC
let isNaN = (value: WasmF64) => {
WasmF64.ne(value, value)
}
let makeNaNError = () => Some(InvalidNumber("NaN is not allowed in JSONNumber"))
let makeInfError = () =>
Some(InvalidNumber("Infinity is not allowed in JSONNumber"))
let makeNegInfError = () =>
Some(InvalidNumber("-Infinity is not allowed in JSONNumber"))
@disableGC
let printNumberWasmF64 = (value: WasmF64, buffer: Buffer.Buffer) => {
let result = if (isFinite(value)) {
let s = NumberUtils.dtoa(value)
Memory.incRef(WasmI32.fromGrain(Buffer.addString))
Memory.incRef(WasmI32.fromGrain(s))
Memory.incRef(WasmI32.fromGrain(buffer))
Buffer.addString(s, buffer)
Memory.decRef(WasmI32.fromGrain(s))
let none = None
Memory.incRef(WasmI32.fromGrain(none))
none
} else {
// 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
// coninue formatting without representing these values correctly
// (like JavaScript's JSON.stringify).
if (isNaN(value)) {
// Allocating the exception in a function without @disableGC makes
// it easier to avoid problems with reference counting.
Memory.incRef(WasmI32.fromGrain(makeNaNError))
makeNaNError()
} else if (WasmF64.lt(value, 0.0W)) {
Memory.incRef(WasmI32.fromGrain(makeNegInfError))
makeNegInfError()
} else {
Memory.incRef(WasmI32.fromGrain(makeInfError))
makeInfError()
}
}
result
}
@disableGC
let rec printNumber = (value: Number, buffer: Buffer.Buffer) => {
let (&) = WasmI32.and
let (==) = WasmI32.eq
let (!=) = WasmI32.ne
let (<<) = WasmI32.shl
let (>>) = WasmI32.shrS
let ptr = WasmI32.fromGrain(value)
let result = if ((ptr & 1n) != 0n) {
// FIXME expose runtime/numbers.untagSimple?
let asWasmI32 = ptr >> 1n
printNumberWasmI32(asWasmI32, buffer)
} 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_INT32_BOXED_NUM_TAG => {
let asWasmI32 = WasmI32.load(ptr, 8n)
// FIXME magic numbers
printNumberWasmI32(asWasmI32, buffer)
},
t when t == Tags._GRAIN_INT64_BOXED_NUM_TAG => {
let asWasmI64 = WasmI64.load(ptr, 8n)
// FIXME magic numbers
printNumberWasmI64(asWasmI64, buffer)
},
t when t == Tags._GRAIN_RATIONAL_BOXED_NUM_TAG => {
// As a compromnise, convert the rational into a float
// and then print that. This means there can be
// precision loss even for values that could be printed
// exactly in decimal notation, but doing otherwise
// could both compromise perfomance and confuse
// developers as most JSON libraries in other languages
// likely only deal with integers and floats.
// Note that the ECMA-404 standard only specifies how
// numbers should be formatted as text (in decimal
// notation), so we could go the extra mile and at
// least for some numbers try printing the exact
// number. For example those that have a power of 10
// in the denominator.
let asWasmF64 = WasmF64.div(
WasmF64.convertI32S(Numbers.boxedRationalNumerator(ptr)),
WasmF64.convertI32S(Numbers.boxedRationalDenominator(ptr))
)
printNumberWasmF64(asWasmF64, buffer)
},
t when t == Tags._GRAIN_FLOAT32_BOXED_NUM_TAG => {
let asWasmF32 = WasmF32.load(ptr, 8n)
// FIXME magic numbers
let asWasmF64 = WasmF64.promoteF32(asWasmF32)
printNumberWasmF64(asWasmF64, buffer)
},
t when t == Tags._GRAIN_FLOAT64_BOXED_NUM_TAG => {
let asWasmF64 = WasmF64.load(ptr, 8n)
// FIXME magic numbers
printNumberWasmF64(asWasmF64, buffer)
},
_ => {
throw UnknownNumberTag
},
}
},
_ => {
throw UnknownNumberTag
},
}
} else {
throw UnknownNumberTag
}
Memory.decRef(WasmI32.fromGrain(value))
Memory.decRef(WasmI32.fromGrain(buffer))
Memory.decRef(WasmI32.fromGrain(printNumber))
result
}
// Note that this function is not allocated with the JSONWriter because currently
// Grain leaks memory each time a recursive closure is allocated. Not reallocating
// it may also be a better thing to do.
let rec printElementCompact =
(
json: JSON,
implHelper: JSONWriterCompactImplHelper,
) => {
let buffer = implHelper.buffer
match (json) {
JSONNull => {
printNull(buffer)
None
},
JSONBoolean(b) => {
printBool(b, buffer)
None
},
JSONNumber(n) => printNumber(n, buffer),
JSONString(s) => {
implHelper.emitEscapedQuotedString(s)
None
},
JSONArray(elems) => {
// Here I'm not using List.forEachi or similar in order to avoid
// allocations of closures. The code is verbose and a bit ugly as a
// consequence, but I think it's an OK price for performance gain.
// Another approach would be to allocate a function for the
// formattng arrays just once at the start of formatting and pass
// it in emitJSONElement.
match (elems) {
[] => {
Buffer.addChar('[', buffer)
Buffer.addChar(']', buffer)
None
},
[e] => {
Buffer.addChar('[', buffer)
let err = printElementCompact(e, implHelper)
if (Option.isNone(err)) {
Buffer.addChar(']', buffer)
}
err
},
[initialHead, ...initialRest] => {
Buffer.addChar('[', buffer)
let mut currentHead = initialHead
let mut currentRest = initialRest
let mut err = None
for (let mut index = 0; ; index += 1) {
if (index > 0) {
Buffer.addChar(',', buffer)
}
err = printElementCompact(currentHead, implHelper)
if (Option.isSome(err)) break
match (currentRest) {
[] => break,
[newHead, ...newRest] => {
currentHead = newHead
currentRest = newRest
},
}
}
if (Option.isNone(err)) {
Buffer.addChar(']', buffer)
}
err
},
}
},
JSONObject(entries) => {
match (entries) {
[] => {
Buffer.addChar('{', buffer)
Buffer.addChar('}', buffer)
None
},
[(key, value)] => {
Buffer.addChar('{', buffer)
implHelper.emitEscapedQuotedString(key)
Buffer.addChar(':', buffer)
let err = printElementCompact(value, implHelper)
if (Option.isNone(err)) {
Buffer.addChar('}', buffer)
}
err
},
[initialHead, ...initialRest] => {
Buffer.addChar('{', buffer)
let mut currentHead = initialHead
let mut currentRest = initialRest
let mut err = None
for (let mut index = 0; ; index += 1) {
if (index > 0) {
Buffer.addChar(',', buffer)
}
let (key, value) = currentHead
implHelper.emitEscapedQuotedString(key)
Buffer.addChar(':', buffer)
err = printElementCompact(value, implHelper)
if (Option.isSome(err)) {
break
}
match (currentRest) {
[] => break,
[newHead, ...newRest] => {
currentHead = newHead
currentRest = newRest
},
}
}
if (Option.isNone(err)) {
Buffer.addChar('}', buffer)
}
err
},
}
},
}
}
let makeCompactJSONWriter = (buffer: Buffer.Buffer) => {
// As an optimization prepare a closure function to execute for each code
// point of the input. It's important that this is not inlide in the
// emitEscapedQuotedString function directly to avoid allocating the closue
// for each input string.
let emitCodePoint = (codePoint: Number) => {
// For the compact formatting only escape backslash, double quotes and
// code points 0..31 (the so called "C0" control point group) as
// required by ECMA-404. For the non pretty printed case we don't want
// to escape more than what is stricty required to avoid increasing the
// output size.
if (codePoint > 31 && codePoint != 0x0022 && codePoint != 0x005C) {
addCharFromCodePoint(codePoint, buffer)
} else {
emitEscapedCodePoint(codePoint, buffer)
}
}
let emitEscapedQuotedString = (s: String) => {
Buffer.addChar('"', buffer)
String.forEachCodePoint(emitCodePoint, s)
Buffer.addChar('"', buffer)
}
let implHelper = {
buffer,
emitEscapedQuotedString: s => {
emitEscapedQuotedString(s)
},
}: JSONWriterCompactImplHelper
{
emit: json => {
let error = printElementCompact(json, implHelper)
error
},
}: JSONWriter
}
// Note that this could relatively easily be integrated with
// printElementCompact to avoid code duplication, but it would mean
// compromising peak performance and also increasing complexity in other ways.
let rec printElementPretty =
(
json: JSON,
implHelper: JSONWriterPrettyImplHelper,
indentationLevel: Number,
) => {
let buffer = implHelper.bufferPretty
match (json) {
JSONNull => {
printNull(buffer)
None
},
JSONBoolean(b) => {
printBool(b, buffer)
None
},
JSONNumber(n) => printNumber(n, buffer),
JSONString(s) => {
implHelper.emitEscapedQuotedStringPretty(s)
None
},
JSONArray(elems) => {
match (elems) {
[] => {
Buffer.addChar('[', buffer)
Buffer.addChar(']', buffer)
None
},
[e] => {
let format = implHelper.format
Buffer.addChar('[', buffer)
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printNewLine()
}
let elemLevel = indentationLevel + 1
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printIndentation(elemLevel)
}
let err = printElementPretty(e, implHelper, elemLevel)
if (Option.isNone(err)) {
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printNewLine()
implHelper.printIndentation(indentationLevel)
}
Buffer.addChar(']', buffer)
}
err
},
[initialHead, ...initialRest] => {
let format = implHelper.format
Buffer.addChar('[', buffer)
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printNewLine()
}
let mut currentHead = initialHead
let mut currentRest = initialRest
let mut err = None
let elemLevel = indentationLevel + 1
for (let mut index = 0; ; index += 1) {
if (index > 0) {
Buffer.addChar(',', buffer)
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printNewLine()
}
}
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printIndentation(elemLevel)
}
err = printElementPretty(currentHead, implHelper, elemLevel)
if (Option.isSome(err)) {
break
}
match (currentRest) {
[] => break,
[newHead, ...newRest] => {
currentHead = newHead
currentRest = newRest
},
}
}
if (Option.isNone(err)) {
if (format.arrayFormat == OneArrayEntryPerLine) {
implHelper.printNewLine()
implHelper.printIndentation(indentationLevel)
}
Buffer.addChar(']', buffer)
}
err
},
}
},
JSONObject(entries) => {
match (entries) {
[] => {
Buffer.addChar('{', buffer)
Buffer.addChar('}', buffer)
None
},
[(key, value)] => {
let format = implHelper.format
Buffer.addChar('{', buffer)
let elemLevel = indentationLevel + 1
if (format.objectFormat == OneObjectEntryPerLine) {
implHelper.printNewLine()
implHelper.printIndentation(elemLevel)
}
implHelper.emitEscapedQuotedStringPretty(key)
match (format.objectFormat) {
CompactObjectEntries => {
Buffer.addChar(':', buffer)
},
OneObjectEntryPerLine => {
Buffer.addChar(':', buffer)
Buffer.addChar(' ', buffer)
},
}
let err = printElementPretty(value, implHelper, elemLevel)
if (Option.isNone(err)) {
if (format.objectFormat == OneObjectEntryPerLine) {
implHelper.printNewLine()