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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
|
(;module: {#;doc "Functionality for reading, generating and processing values in the JSON format.
For more information, please see: http://www.json.org/"}
lux
(lux (control functor
applicative
monad
eq
codec)
(data [bool]
[text "Text/" Eq<Text> Monoid<Text>]
text/format
(text [lexer #+ Lexer Monad<Lexer>])
[number #* "Real/" Codec<Text,Real>]
maybe
[char "Char/" Eq<Char> Codec<Text,Char>]
[error #- fail]
[sum]
[product]
(coll [list "" Fold<List> "List/" Monad<List>]
[vector #+ Vector vector "Vector/" Monad<Vector>]
[dict #+ Dict]))
[macro #+ Monad<Lux> with-gensyms]
(macro [syntax #+ syntax:]
[ast]
[poly #+ poly:])
[type]
))
## [Types]
(do-template [<name> <type>]
[(type: #export <name> <type>)]
[Null Unit]
[Boolean Bool]
[Number Real]
[String Text]
)
(type: #export #rec JSON
(#Null Null)
(#Boolean Boolean)
(#Number Number)
(#String String)
(#Array (Vector JSON))
(#Object (Dict String JSON)))
(do-template [<name> <type>]
[(type: #export <name> <type>)]
[Array (Vector JSON)]
[Object (Dict String JSON)]
)
(type: #export (Parser a)
{#;doc "JSON parsers."}
(-> JSON (Error a)))
(type: #export (Gen a)
{#;doc "JSON generators."}
(-> a JSON))
## [Syntax]
(syntax: #export (json token)
{#;doc (doc "A way to produce JSON literals."
(json true)
(json 123)
(json 456.78)
(json "Some text")
(json #null)
(json ["this" "is" "an" "array"])
(json {"this" "is"
"an" "object"}))}
(let [(^open) Monad<Lux>
wrapper (function [x] (` (;;json (~ x))))]
(case token
(^template [<ast-tag> <ctor> <json-tag>]
[_ (<ast-tag> value)]
(wrap (list (` (: JSON (<json-tag> (~ (<ctor> value))))))))
([#;BoolS ast;bool #Boolean]
[#;IntS (|>. int-to-real ast;real) #Number]
[#;RealS ast;real #Number]
[#;TextS ast;text #String])
[_ (#;TagS ["" "null"])]
(wrap (list (` (: JSON #Null))))
[_ (#;TupleS members)]
(wrap (list (` (: JSON (#Array (vector (~@ (List/map wrapper members))))))))
[_ (#;RecordS pairs)]
(do Monad<Lux>
[pairs' (mapM @
(function [[slot value]]
(case slot
[_ (#;TextS key-name)]
(wrap (` [(~ (ast;text key-name)) (~ (wrapper value))]))
_
(macro;fail "Wrong syntax for JSON object.")))
pairs)]
(wrap (list (` (: JSON (#Object (dict;from-list text;Hash<Text> (list (~@ pairs')))))))))
_
(wrap (list token))
)))
## [Values]
(def: #hidden (show-null _) (-> Null Text) "null")
(do-template [<name> <type> <codec>]
[(def: <name> (-> <type> Text) (:: <codec> encode))]
[show-boolean Boolean bool;Codec<Text,Bool>]
[show-number Number number;Codec<Text,Real>]
[show-string String text;Codec<Text,Text>])
(def: (show-array show-json elems)
(-> (-> JSON Text) (-> Array Text))
(format "["
(|> elems (Vector/map show-json) vector;to-list (text;join-with ","))
"]"))
(def: (show-object show-json object)
(-> (-> JSON Text) (-> Object Text))
(format "{"
(|> object
dict;entries
(List/map (function [[key value]] (format (:: text;Codec<Text,Text> encode key) ":" (show-json value))))
(text;join-with ","))
"}"))
(def: (show-json json)
(-> JSON Text)
(case json
(^template [<tag> <show>]
(<tag> value)
(<show> value))
([#Null show-null]
[#Boolean show-boolean]
[#Number show-number]
[#String show-string]
[#Array (show-array show-json)]
[#Object (show-object show-json)])
))
(def: #export null
{#;doc "The null JSON value."}
JSON
#Null)
(def: #export (fields json)
{#;doc "Get all the fields in a JSON object."}
(-> JSON (Error (List String)))
(case json
(#Object obj)
(#;Right (dict;keys obj))
_
(#;Left (format "Cannot get the fields of a non-object."))))
(def: #export (get key json)
{#;doc "A JSON object field getter."}
(-> String JSON (Error JSON))
(case json
(#Object obj)
(case (dict;get key obj)
(#;Some value)
(#;Right value)
#;None
(#;Left (format "Missing field " (show-string key) " on object.")))
_
(#;Left (format "Cannot get field " (show-string key) " of a non-object."))))
(def: #export (set key value json)
{#;doc "A JSON object field setter."}
(-> String JSON JSON (Error JSON))
(case json
(#Object obj)
(#;Right (#Object (dict;put key value obj)))
_
(#;Left (format "Cannot set field " (show-string key) " of a non-object."))))
(do-template [<name> <tag> <type> <desc>]
[(def: #export (<name> key json)
{#;doc (#;TextA (format "A JSON object field getter for " <desc> "."))}
(-> Text JSON (Error <type>))
(case (get key json)
(#;Right (<tag> value))
(#;Right value)
(#;Right _)
(#;Left (format "Wrong value type at key " (show-string key)))
(#;Left error)
(#;Left error)))]
[get-boolean #Boolean Boolean "booleans"]
[get-number #Number Number "numbers"]
[get-string #String String "strings"]
[get-array #Array Array "arrays"]
[get-object #Object Object "objects"]
)
(do-template [<name> <type> <tag> <desc>]
[(def: #export (<name> value)
{#;doc (#;TextA (format "A JSON generator for " <desc> "."))}
(Gen <type>)
(<tag> value))]
[gen-boolean Boolean #Boolean "booleans"]
[gen-number Number #Number "numbers"]
[gen-string String #String "strings"]
[gen-array Array #Array "arrays"]
[gen-object Object #Object "objects"]
)
(def: #export (gen-nullable gen)
{#;doc "Builds a JSON generator for potentially inexistent values."}
(All [a] (-> (Gen a) (Gen (Maybe a))))
(function [elem]
(case elem
#;None #Null
(#;Some value) (gen value))))
## Lexers
(def: space~
(Lexer Text)
(lexer;some' lexer;space))
(def: data-sep
(Lexer [Text Char Text])
($_ lexer;seq space~ (lexer;char #",") space~))
(def: null~
(Lexer Null)
(do Monad<Lexer>
[_ (lexer;text "null")]
(wrap [])))
(do-template [<name> <token> <value>]
[(def: <name>
(Lexer Boolean)
(do Monad<Lexer>
[_ (lexer;text <token>)]
(wrap <value>)))]
[t~ "true" true]
[f~ "false" false]
)
(def: boolean~
(Lexer Boolean)
(lexer;either t~ f~))
(def: number~
(Lexer Number)
(do Monad<Lexer>
[?sign (: (Lexer Text)
(lexer;default ""
(lexer;text "-")))
digits (: (Lexer Text)
(lexer;many' lexer;digit))
decimals (: (Lexer Text)
(lexer;default "0"
(do @
[_ (lexer;text ".")]
(lexer;many' lexer;digit))))
exp (: (Lexer Text)
(lexer;default ""
(do @
[mark (lexer;either (lexer;text "e") (lexer;text "E"))
sign (lexer;default "" (lexer;text "-"))
offset (lexer;many' lexer;digit)]
(wrap (format mark sign offset)))))]
(case (: (Error Real)
(Real/decode (format ?sign digits "." decimals exp)))
(#;Left message)
(lexer;fail message)
(#;Right value)
(wrap value))))
(def: (un-escape escaped)
(-> Char Text)
(case escaped
#"t" "\t"
#"b" "\b"
#"n" "\n"
#"r" "\r"
#"f" "\f"
#"\"" "\""
#"\\" "\\"
_ ""))
(def: string-body~
(Lexer Text)
(loop [_ []]
(do Monad<Lexer>
[chars (lexer;some' (lexer;none-of "\\\""))
stop-char lexer;peek]
(if (Char/= #"\\" stop-char)
(do @
[_ lexer;any
escaped lexer;any
next-chars (recur [])]
(wrap (format chars (un-escape escaped) next-chars)))
(wrap chars)))))
(def: string~
(Lexer String)
(do Monad<Lexer>
[_ (lexer;text "\"")
string-body string-body~
_ (lexer;text "\"")]
(wrap string-body)))
(def: (kv~ json~)
(-> (-> Unit (Lexer JSON)) (Lexer [String JSON]))
(do Monad<Lexer>
[key string~
_ space~
_ (lexer;char #":")
_ space~
value (json~ [])]
(wrap [key value])))
(do-template [<name> <type> <open> <close> <elem-parser> <prep>]
[(def: (<name> json~)
(-> (-> Unit (Lexer JSON)) (Lexer <type>))
(do Monad<Lexer>
[_ (lexer;char <open>)
_ space~
elems (lexer;sep-by data-sep <elem-parser>)
_ space~
_ (lexer;char <close>)]
(wrap (<prep> elems))))]
[array~ Array #"[" #"]" (json~ []) vector;from-list]
[object~ Object #"{" #"}" (kv~ json~) (dict;from-list text;Hash<Text>)]
)
(def: (json~' _)
(-> Unit (Lexer JSON))
($_ lexer;alt null~ boolean~ number~ string~ (array~ json~') (object~ json~')))
## [Structures]
(struct: #export _ (Functor Parser)
(def: (map f ma)
(function [json]
(case (ma json)
(#;Left msg)
(#;Left msg)
(#;Right a)
(#;Right (f a))))))
(struct: #export _ (Applicative Parser)
(def: functor Functor<Parser>)
(def: (wrap x json)
(#;Right x))
(def: (apply ff fa)
(function [json]
(case (ff json)
(#;Right f)
(case (fa json)
(#;Right a)
(#;Right (f a))
(#;Left msg)
(#;Left msg))
(#;Left msg)
(#;Left msg)))))
(struct: #export _ (Monad Parser)
(def: applicative Applicative<Parser>)
(def: (join mma)
(function [json]
(case (mma json)
(#;Left msg)
(#;Left msg)
(#;Right ma)
(ma json)))))
## [Values]
## Syntax
(do-template [<name> <type> <tag> <desc> <pre>]
[(def: #export (<name> json)
{#;doc (#;TextA (format "Reads a JSON value as " <desc> "."))}
(Parser <type>)
(case json
(<tag> value)
(#;Right (<pre> value))
_
(#;Left (format "JSON value is not " <desc> ": " (show-json json)))))]
[unit Unit #Null "unit" id]
[bool Bool #Boolean "bool" id]
[int Int #Number "int" real-to-int]
[real Real #Number "real" id]
[text Text #String "text" id]
)
(do-template [<test> <check> <type> <eq> <codec> <tag> <desc> <pre>]
[(def: #export (<test> test json)
{#;doc (#;TextA (format "Asks whether a JSON value is a " <desc> "."))}
(-> <type> (Parser Bool))
(case json
(<tag> value)
(#;Right (:: <eq> = test (<pre> value)))
_
(#;Left (format "JSON value is not a " <desc> ": " (show-json json)))))
(def: #export (<check> test json)
{#;doc (#;TextA (format "Ensures a JSON value is a " <desc> "."))}
(-> <type> (Parser Unit))
(case json
(<tag> value)
(let [value (<pre> value)]
(if (:: <eq> = test value)
(#;Right [])
(#;Left (format "Value mismatch: "
(:: <codec> encode test) "=/=" (:: <codec> encode value)))))
_
(#;Left (format "JSON value is not a " <desc> ": " (show-json json)))))]
[bool? bool! Bool bool;Eq<Bool> bool;Codec<Text,Bool> #Boolean "boolean" id]
[int? int! Int number;Eq<Int> number;Codec<Text,Int> #Number "number" real-to-int]
[real? real! Real number;Eq<Real> number;Codec<Text,Real> #Number "number" id]
[text? text! Text text;Eq<Text> text;Codec<Text,Text> #String "string" id]
)
(def: #export (char json)
{#;doc "Reads a JSON value as a single-character string."}
(Parser Char)
(case json
(#String input)
(case (Char/decode (format "#\"" input "\""))
(#;Right value)
(#;Right value)
(#;Left _)
(#;Left (format "Invalid format for char: " input)))
_
(#;Left (format "JSON value is not a " "string" ": " (show-json json)))))
(def: #export (char? test json)
{#;doc "Asks whether a JSON value is a single-character string with the specified character."}
(-> Char (Parser Bool))
(case json
(#String input)
(case (Char/decode (format "#\"" input "\""))
(#;Right value)
(if (:: char;Eq<Char> = test value)
(#;Right true)
(#;Left (format "Value mismatch: "
(:: char;Codec<Text,Char> encode test) "=/=" (:: char;Codec<Text,Char> encode value))))
(#;Left _)
(#;Left (format "Invalid format for char: " input)))
_
(#;Left (format "JSON value is not a " "string" ": " (show-json json)))))
(def: #export (char! test json)
{#;doc "Ensures a JSON value is a single-character string with the specified character."}
(-> Char (Parser Unit))
(case json
(#String input)
(case (Char/decode (format "#\"" input "\""))
(#;Right value)
(if (:: char;Eq<Char> = test value)
(#;Right [])
(#;Left (format "Value mismatch: "
(:: char;Codec<Text,Char> encode test) "=/=" (:: char;Codec<Text,Char> encode value))))
(#;Left _)
(#;Left (format "Invalid format for char: " input)))
_
(#;Left (format "JSON value is not a " "string" ": " (show-json json)))))
(def: #export (nullable parser)
{#;doc "A parser that can handle the presence of null values."}
(All [a] (-> (Parser a) (Parser (Maybe a))))
(function [json]
(case json
#Null
(#;Right #;None)
_
(case (parser json)
(#;Left error)
(#;Left error)
(#;Right value)
(#;Right (#;Some value)))
)))
(def: #export (array parser)
{#;doc "Parses a JSON array, assuming that every element can be parsed the same way."}
(All [a] (-> (Parser a) (Parser (List a))))
(function [json]
(case json
(#Array values)
(do Monad<Error>
[elems (mapM @ parser (vector;to-list values))]
(wrap elems))
_
(#;Left (format "JSON value is not an array: " (show-json json))))))
(def: #export (object parser)
{#;doc "Parses a JSON object, assuming that every field's value can be parsed the same way."}
(All [a] (-> (Parser a) (Parser (Dict String a))))
(function [json]
(case json
(#Object fields)
(do Monad<Error>
[kvs (mapM @
(function [[key val']]
(do @
[val (parser val')]
(wrap [key val])))
(dict;entries fields))]
(wrap (dict;from-list text;Hash<Text> kvs)))
_
(#;Left (format "JSON value is not an object: " (show-json json))))))
(def: #export (nth idx parser)
{#;doc "Parses an element inside a JSON array."}
(All [a] (-> Nat (Parser a) (Parser a)))
(function [json]
(case json
(#Array values)
(case (vector;nth idx values)
(#;Some value)
(case (parser value)
(#;Right output)
(#;Right output)
(#;Left error)
(#;Left (format "JSON array index [" (%n idx) "]: (" error ") @ " (show-json json))))
#;None
(#;Left (format "JSON array does not have index " (%n idx) " @ " (show-json json))))
_
(#;Left (format "JSON value is not an array: " (show-json json))))))
(def: #export (field field-name parser)
{#;doc "Parses a field inside a JSON object."}
(All [a] (-> Text (Parser a) (Parser a)))
(function [json]
(case (get field-name json)
(#;Some value)
(case (parser value)
(#;Right output)
(#;Right output)
(#;Left error)
(#;Left (format "Failed to get JSON object field " (show-string field-name) ": (" error ") @ " (show-json json))))
(#;Left _)
(#;Left (format "JSON object does not have field " (show-string field-name) " @ " (show-json json))))))
(def: #export any
{#;doc "Just returns the JSON input without applying any logic."}
(Parser JSON)
(function [json]
(#;Right json)))
(def: #export (seq pa pb)
{#;doc "Sequencing combinator."}
(All [a b] (-> (Parser a) (Parser b) (Parser [a b])))
(do Monad<Parser>
[=a pa
=b pb]
(wrap [=a =b])))
(def: #export (alt pa pb json)
{#;doc "Heterogeneous alternative combinator."}
(All [a b] (-> (Parser a) (Parser b) (Parser (| a b))))
(case (pa json)
(#;Right a)
(sum;right (sum;left a))
(#;Left message0)
(case (pb json)
(#;Right b)
(sum;right (sum;right b))
(#;Left message1)
(#;Left message0))))
(def: #export (either pl pr json)
{#;doc "Homogeneous alternative combinator."}
(All [a] (-> (Parser a) (Parser a) (Parser a)))
(case (pl json)
(#;Right x)
(#;Right x)
_
(pr json)))
(def: #export (opt p json)
{#;doc "Optionality combinator."}
(All [a]
(-> (Parser a) (Parser (Maybe a))))
(case (p json)
(#;Left _) (#;Right #;None)
(#;Right x) (#;Right (#;Some x))))
(def: #export (run json parser)
(All [a] (-> JSON (Parser a) (Error a)))
(parser json))
(def: #export (ensure test parser json)
{#;doc "Only parses a JSON if it passes a test (which is also a parser)."}
(All [a] (-> (Parser Unit) (Parser a) (Parser a)))
(case (test json)
(#;Right _)
(parser json)
(#;Left error)
(#;Left error)))
(def: #export (array-size! size json)
{#;doc "Ensures a JSON array has the specified size."}
(-> Nat (Parser Unit))
(case json
(#Array parts)
(if (n.= size (vector;size parts))
(#;Right [])
(#;Left (format "JSON array does no have size " (%n size) " " (show-json json))))
_
(#;Left (format "JSON value is not an array: " (show-json json)))))
(def: #export (object-fields! wanted-fields json)
{#;doc "Ensures that every field in the list of wanted-fields is present in a JSON object."}
(-> (List String) (Parser Unit))
(case json
(#Object kvs)
(let [actual-fields (dict;keys kvs)]
(if (and (n.= (list;size wanted-fields) (list;size actual-fields))
(list;every? (list;member? text;Eq<Text> wanted-fields)
actual-fields))
(#;Right [])
(#;Left (format "JSON object has wrong field-set. Expected: [" (text;join-with ", " wanted-fields) "]. Actual: [" (text;join-with ", " actual-fields) "]"))))
_
(#;Left (format "JSON value is not an object: " (show-json json)))))
## [Structures]
(struct: #export _ (Eq JSON)
(def: (= x y)
(case [x y]
[#Null #Null]
true
(^template [<tag> <struct>]
[(<tag> x') (<tag> y')]
(:: <struct> = x' y'))
([#Boolean bool;Eq<Bool>]
[#Number number;Eq<Real>]
[#String text;Eq<Text>])
[(#Array xs) (#Array ys)]
(and (n.= (vector;size xs) (vector;size ys))
(fold (function [idx prev]
(and prev
(default false
(do Monad<Maybe>
[x' (vector;nth idx xs)
y' (vector;nth idx ys)]
(wrap (= x' y'))))))
true
(list;indices (vector;size xs))))
[(#Object xs) (#Object ys)]
(and (n.= (dict;size xs) (dict;size ys))
(fold (function [[xk xv] prev]
(and prev
(case (dict;get xk ys)
#;None false
(#;Some yv) (= xv yv))))
true
(dict;entries xs)))
_
false)))
(struct: #export _ (Codec Text JSON)
(def: encode show-json)
(def: decode (function [input] (lexer;run input (json~' [])))))
## [Syntax]
(type: Shape
(#ArrayShape (List AST))
(#ObjectShape (List [Text AST])))
(def: _shape^
(syntax;Syntax Shape)
(syntax;alt (syntax;tuple (syntax;some syntax;any))
(syntax;record (syntax;some (syntax;seq syntax;text syntax;any)))))
(syntax: #export (shape [shape _shape^])
{#;doc (doc "Builds a parser that ensures the (inclusive) shape of an array or object."
(shape [bool! int! real!])
(shape {"isAlive" bool!
"age" int!
"income" real!}))}
(case shape
(#ArrayShape parts)
(let [array-size (list;size parts)
parsers (|> parts
(list;zip2 (list;indices array-size))
(List/map (function [[idx parser]]
(` (nth (~ (ast;nat idx)) (~ parser))))))]
(wrap (list (` ($_ seq (~@ parsers))))))
(#ObjectShape kvs)
(let [fields (List/map product;left kvs)
parsers (List/map (function [[field-name parser]]
(` (field (~ (ast;text field-name)) (~ parser))))
kvs)]
(wrap (list (` ($_ seq (~@ parsers))))))
))
(syntax: #export (shape! [shape _shape^])
{#;doc (doc "Builds a parser that ensures the (exclusive) shape of an array or object."
(shape! [bool! int! real!])
(shape! {"isAlive" bool!
"age" int!
"income" real!}))}
(case shape
(#ArrayShape parts)
(let [array-size (list;size parts)
parsers (|> parts
(list;zip2 (list;indices array-size))
(List/map (function [[idx parser]]
(` (nth (~ (ast;nat idx)) (~ parser))))))]
(wrap (list (` (ensure (array-size! (~ (ast;nat array-size)))
($_ seq (~@ parsers)))))))
(#ObjectShape kvs)
(let [fields (List/map product;left kvs)
parsers (List/map (function [[field-name parser]]
(` (field (~ (ast;text field-name)) (~ parser))))
kvs)]
(wrap (list (` (ensure (object-fields! (list (~@ (List/map ast;text fields))))
($_ seq (~@ parsers)))))))
))
## [Polytypism]
(def: #hidden _map_
(All [a b] (-> (-> a b) (List a) (List b)))
List/map)
(poly: #hidden (Codec<JSON,?>//encode *env* :x:)
(let [->Codec//encode (: (-> AST AST)
(function [.type.] (` (-> (~ .type.) JSON))))]
(let% [<basic> (do-template [<type> <matcher> <encoder>]
[(do @ [_ (<matcher> :x:)] (wrap (` (: (~ (->Codec//encode (` <type>))) <encoder>))))]
[Unit poly;unit (function [(~ (ast;symbol ["" "0"]))] #Null)]
[Bool poly;bool ;;gen-boolean]
[Int poly;int (|>. ;int-to-real ;;gen-number)]
[Real poly;real ;;gen-number]
[Char poly;char (|>. char;as-text ;;gen-string)]
[Text poly;text ;;gen-string])]
($_ macro;either
<basic>
(with-gensyms [g!type-fun g!case g!input g!key g!val]
(do @
[:sub: (poly;list :x:)
[g!vars members] (poly;tuple :sub:)
:val: (case members
(^ (list :key: :val:))
(do @ [_ (poly;text :key:)]
(wrap :val:))
_
(macro;fail ""))
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices)
g!vars)
*env*)]
.val. (Codec<JSON,?>//encode new-*env* :val:)
#let [:x:+ (case g!vars
#;Nil
(->Codec//encode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//encode g!vars))
(~ (->Codec//encode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ g!input)]
(|> (~ g!input)
(_map_ (: (-> [Text (~ (type;to-ast :val:))]
[Text JSON])
(function [[(~ g!key) (~ g!val)]]
[(~ g!key)
((~ .val.) (~ g!val))])))
;;object))
)))
))
(do @
[:sub: (poly;maybe :x:)
.sub. (Codec<JSON,?>//encode *env* :sub:)]
(wrap (` (: (~ (->Codec//encode (type;to-ast :x:)))
(;;gen-nullable (~ .sub.))))))
(do @
[:sub: (poly;list :x:)
.sub. (Codec<JSON,?>//encode *env* :sub:)]
(wrap (` (: (~ (->Codec//encode (type;to-ast :x:)))
(|>. (_map_ (~ .sub.)) vector;from-list ;;gen-array)))))
(with-gensyms [g!type-fun g!case g!input]
(do @
[[g!vars members] (poly;variant :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
pattern-matching (mapM @
(function [[name :case:]]
(do @
[#let [tag (ast;tag name)]
encoder (Codec<JSON,?>//encode new-*env* :case:)]
(wrap (list (` ((~ tag) (~ g!case)))
(` (;;json [(~ (ast;text (product;right name)))
((~ encoder) (~ g!case))]))))))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//encode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//encode g!vars))
(~ (->Codec//encode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ g!input)]
(case (~ g!input)
(~@ (List/join pattern-matching))))
)))))
(with-gensyms [g!type-fun g!case g!input]
(do @
[[g!vars members] (poly;record :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
synthesis (mapM @
(function [[name :slot:]]
(do @
[encoder (Codec<JSON,?>//encode new-*env* :slot:)]
(wrap [(` (~ (ast;text (product;right name))))
(` ((~ encoder) (get@ (~ (ast;tag name)) (~ g!input))))])))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//encode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//encode g!vars))
(~ (->Codec//encode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ g!input)]
(;;json (~ (ast;record synthesis))))
)))))
(with-gensyms [g!type-fun g!case]
(do @
[[g!vars members] (poly;tuple :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
pattern-matching (mapM @
(function [:member:]
(do @
[g!member (macro;gensym "g!member")
encoder (Codec<JSON,?>//encode new-*env* :member:)]
(wrap [g!member encoder])))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//encode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//encode g!vars))
(~ (->Codec//encode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]
#let [.tuple. (` [(~@ (List/map product;left pattern-matching))])]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ .tuple.)]
(;;json [(~@ (List/map (function [[g!member g!encoder]]
(` ((~ g!encoder) (~ g!member))))
pattern-matching))]))
)))
))
(do @
[[:func: :args:] (poly;apply :x:)
.func. (Codec<JSON,?>//encode *env* :func:)
.args. (mapM @ (Codec<JSON,?>//encode *env*) :args:)]
(wrap (` (: (~ (->Codec//encode (type;to-ast :x:)))
((~ .func.) (~@ .args.))))))
(poly;bound *env* :x:)
(macro;fail (format "Cannot create JSON encoder for: " (%type :x:)))
))))
(poly: #hidden (Codec<JSON,?>//decode *env* :x:)
(let [->Codec//decode (: (-> AST AST)
(function [.type.] (` (-> JSON (Error (~ .type.))))))]
(let% [<basic> (do-template [<type> <matcher> <decoder>]
[(do @ [_ (<matcher> :x:)] (wrap (` (: (~ (->Codec//decode (` <type>))) <decoder>))))]
[Unit poly;unit ;;unit]
[Bool poly;bool ;;bool]
[Int poly;int ;;int]
[Real poly;real ;;real]
[Char poly;char ;;char]
[Text poly;text ;;text])
<complex> (do-template [<type> <matcher> <decoder>]
[(do @
[:sub: (<matcher> :x:)
.sub. (Codec<JSON,?>//decode *env* :sub:)]
(wrap (` (: (~ (->Codec//decode (type;to-ast :x:)))
(<decoder> (~ .sub.))))))]
[Maybe poly;maybe ;;nullable]
[List poly;list ;;array])]
($_ macro;either
<basic>
(with-gensyms [g!type-fun g!case g!input g!key g!val]
(do @
[:sub: (poly;list :x:)
[g!vars members] (poly;tuple :sub:)
:val: (case members
(^ (list :key: :val:))
(do @ [_ (poly;text :key:)]
(wrap :val:))
_
(macro;fail ""))
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
.val. (Codec<JSON,?>//decode new-*env* :val:)
#let [:x:+ (case g!vars
#;Nil
(->Codec//decode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//decode g!vars))
(~ (->Codec//decode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ g!input)]
(do Monad<Error>
[(~ g!key) (;;fields (~ g!input))]
(mapM (~ (' %))
(function [(~ g!key)]
(do Monad<Error>
[(~ g!val) (;;get (~ g!key) (~ g!input))
(~ g!val) (;;run (~ g!val) (~ .val.))]
((~ (' wrap)) [(~ g!key) (~ g!val)])))
(~ g!key))))
)))
))
<complex>
(with-gensyms [g!type-fun g!_]
(do @
[[g!vars members] (poly;variant :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
pattern-matching (mapM @
(function [[name :case:]]
(do @
[#let [tag (ast;tag name)]
decoder (Codec<JSON,?>//decode new-*env* :case:)]
(wrap (list (` (do Monad<Parser>
[(~ g!_) (;;nth +0 (;;text! (~ (ast;text (product;right name)))))
(~ g!_) (;;nth +1 (~ decoder))]
((~ (' wrap)) ((~ tag) (~ g!_)))))))))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//decode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//decode g!vars))
(~ (->Codec//decode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))
base-parser (` ($_ ;;either
(~@ (List/join pattern-matching))))
parser (case g!vars
#;Nil
base-parser
_
(` (function [(~@ g!vars)] (~ base-parser))))]]
(wrap (` (: (~ :x:+) (~ parser))))
))
(with-gensyms [g!type-fun g!case g!input]
(do @
[[g!vars members] (poly;record :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
extraction (mapM @
(function [[name :slot:]]
(do @
[#let [g!member (ast;symbol ["" (product;right name)])]
decoder (Codec<JSON,?>//decode new-*env* :slot:)]
(wrap (list g!member
(` (;;get (~ (ast;text (product;right name))) (~ g!input)))
g!member
(` ((~ decoder) (~ g!member)))))))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//decode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//decode g!vars))
(~ (->Codec//decode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]]
(wrap (` (: (~ :x:+)
(function [(~@ g!vars) (~ g!input)]
(do Monad<Error>
[(~@ (List/join extraction))]
((~ (' wrap)) (~ (ast;record (List/map (function [[name :slot:]]
[(ast;tag name) (ast;symbol ["" (product;right name)])])
members))))))
)))))
(with-gensyms [g!type-fun g!case g!input]
(do @
[[g!vars members] (poly;tuple :x:)
#let [new-*env* (poly;extend-env [:x: g!type-fun]
(list;zip2 (|> g!vars list;size poly;type-var-indices) g!vars)
*env*)]
pattern-matching (mapM @
(function [:member:]
(do @
[g!member (macro;gensym "g!member")
decoder (Codec<JSON,?>//decode new-*env* :member:)]
(wrap [g!member decoder])))
members)
#let [:x:+ (case g!vars
#;Nil
(->Codec//decode (type;to-ast :x:))
_
(` (All (~ g!type-fun) [(~@ g!vars)]
(-> (~@ (List/map ->Codec//decode g!vars))
(~ (->Codec//decode (` ((~ (type;to-ast :x:)) (~@ g!vars)))))))))]
#let [.decoder. (case g!vars
#;Nil
(` (;;shape [(~@ (List/map product;right pattern-matching))]))
_
(` (function [(~@ g!vars)]
(;;shape [(~@ (List/map product;right pattern-matching))]))))]]
(wrap (` (: (~ :x:+) (~ .decoder.))))
))
(do @
[[:func: :args:] (poly;apply :x:)
.func. (Codec<JSON,?>//decode *env* :func:)
.args. (mapM @ (Codec<JSON,?>//decode *env*) :args:)]
(wrap (` (: (~ (->Codec//decode (type;to-ast :x:)))
((~ .func.) (~@ .args.))))))
(do @
[g!bound (poly;bound *env* :x:)]
(wrap g!bound))
(macro;fail (format "Cannot create JSON decoder for: " (%type :x:)))
))))
(syntax: #export (Codec<JSON,?> :x:)
{#;doc (doc "A macro for automatically producing JSON codecs."
(type: Variant
(#Case0 Bool)
(#Case1 Int)
(#Case2 Real))
(type: Record
{#unit Unit
#bool Bool
#int Int
#real Real
#char Char
#text Text
#maybe (Maybe Int)
#list (List Int)
#variant Variant
#tuple [Int Real Char]})
(derived: (Codec<JSON,?> Record)))}
(wrap (list (` (: (Codec JSON (~ :x:))
(struct (def: (~ (' encode)) (Codec<JSON,?>//encode (~ :x:)))
(def: (~ (' decode)) (Codec<JSON,?>//decode (~ :x:)))
))))))
|