aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/macro/poly/json.lux
blob: 1f5b4aab6f9dbe81e72532af49eeb2c1dacc6d9f (plain)
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
(.module: {#.doc "Codecs for values in the JSON format."}
  [lux #*
   [control
    [monad (#+ do Monad)]
    [equivalence (#+ Equivalence)]
    codec
    ["p" parser]]
   [data
    [bit]
    maybe
    ["e" error]
    [sum]
    [product]
    [number ("frac/" Codec<Text,Frac>) ("nat/" Codec<Text,Nat>)
     [i64]]
    [text ("text/" Equivalence<Text>)
     ["l" lexer]
     format]
    [format ["//" json (#+ JSON)]]
    [collection
     [list ("list/" Fold<List> Monad<List>)]
     [row (#+ Row row) ("row/" Monad<Row>)]
     ["d" dictionary]]]
   [time
    ## ["i" instant]
    ["du" duration]
    ["da" date]]
   [macro (#+ with-gensyms)
    ["s" syntax (#+ syntax:)]
    [code]
    [poly (#+ poly:)]]
   [type [unit]]
   [language [type]]])

(def: tag
  (-> Nat Frac)
  (|>> .int int-to-frac))

(def: (rec-encode non-rec)
  (All [a] (-> (-> (-> a JSON)
                   (-> a JSON))
               (-> a JSON)))
  (function (_ input)
    (non-rec (rec-encode non-rec) input)))

(def: low-mask Nat (|> +1 (i64.left-shift +32) dec))
(def: high-mask Nat (|> low-mask (i64.left-shift +32)))

(structure: _ (Codec JSON Nat)
  (def: (encode input)
    (let [high (|> input (i64.and high-mask) (i64.logical-right-shift +32))
          low (i64.and low-mask input)]
      (#//.Array (row (|> high .int int-to-frac #//.Number)
                      (|> low .int int-to-frac #//.Number)))))
  (def: (decode input)
    (<| (//.run input)
        //.array
        (do p.Monad<Parser>
          [high //.number
           low //.number])
        (wrap (n/+ (|> high frac-to-int .nat (i64.left-shift +32))
                   (|> low frac-to-int .nat))))))

(structure: _ (Codec JSON Int)
  (def: encode (|>> .nat (:: Codec<JSON,Nat> encode)))
  (def: decode
    (|>> (:: Codec<JSON,Nat> decode) (:: e.Functor<Error> map .int))))

(def: (nullable writer)
  {#.doc "Builds a JSON generator for potentially inexistent values."}
  (All [a] (-> (-> a JSON) (-> (Maybe a) JSON)))
  (function (_ elem)
    (case elem
      #.None         #//.Null
      (#.Some value) (writer value))))

(structure: Codec<JSON,Qty>
  (All [unit] (Codec JSON (unit.Qty unit)))
  (def: encode
    (|>> unit.out (:: Codec<JSON,Int> encode)))
  (def: decode
    (|>> (:: Codec<JSON,Int> decode) (:: e.Functor<Error> map unit.in))))

(poly: Codec<JSON,?>//encode
  (with-expansions
    [<basic> (do-template [<matcher> <encoder>]
               [(do @
                  [#let [g!_ (code.local-symbol "_______")]
                   _ <matcher>]
                  (wrap (` (: (~ (@JSON//encode inputT))
                              <encoder>))))]

               [(poly.exactly Any) (function ((~ g!_) (~ (code.symbol ["" "0"]))) #//.Null)]
               [(poly.similar Bit) (|>> #//.Boolean)]
               [(poly.similar Nat)  (:: (~! ..Codec<JSON,Nat>) (~' encode))]
               [(poly.similar Int)  (:: (~! ..Codec<JSON,Int>) (~' encode))]
               [(poly.similar Frac) (|>> #//.Number)]
               [(poly.similar Text) (|>> #//.String)])
     <time> (do-template [<type> <codec>]
              [(do @
                 [_ (poly.exactly <type>)]
                 (wrap (` (: (~ (@JSON//encode inputT))
                             (|>> (:: <codec> (~' encode)) #//.String)))))]

              [du.Duration du.Codec<Text,Duration>]
              ## [i.Instant   i.Codec<Text,Instant>]
              [da.Date     da.Codec<Text,Date>]
              [da.Day      da.Codec<Text,Day>]
              [da.Month    da.Codec<Text,Month>])]
    (do @
      [*env* poly.env
       #let [@JSON//encode (: (-> Type Code)
                              (function (_ type)
                                (` (-> (~ (poly.to-code *env* type)) //.JSON))))]
       inputT poly.peek]
      ($_ p.either
          <basic>
          <time>
          (do @
            [unitT (poly.apply (p.after (poly.exactly unit.Qty)
                                        poly.any))]
            (wrap (` (: (~ (@JSON//encode inputT))
                        (:: (~! Codec<JSON,Qty>) (~' encode))))))
          (do @
            [#let [g!_ (code.local-symbol "_______")
                   g!key (code.local-symbol "_______key")
                   g!val (code.local-symbol "_______val")]
             [_ _ =val=] (poly.apply ($_ p.seq
                                         (poly.exactly d.Dictionary)
                                         (poly.exactly .Text)
                                         Codec<JSON,?>//encode))]
            (wrap (` (: (~ (@JSON//encode inputT))
                        (|>> d.entries
                             ((~! list/map) (function ((~ g!_) [(~ g!key) (~ g!val)])
                                              [(~ g!key) ((~ =val=) (~ g!val))]))
                             (d.from-list text.Hash<Text>)
                             #//.Object)))))
          (do @
            [[_ =sub=] (poly.apply ($_ p.seq
                                       (poly.exactly .Maybe)
                                       Codec<JSON,?>//encode))]
            (wrap (` (: (~ (@JSON//encode inputT))
                        ((~! ..nullable) (~ =sub=))))))
          (do @
            [[_ =sub=] (poly.apply ($_ p.seq
                                       (poly.exactly .List)
                                       Codec<JSON,?>//encode))]
            (wrap (` (: (~ (@JSON//encode inputT))
                        (|>> ((~! list/map) (~ =sub=)) row.from-list #//.Array)))))
          (do @
            [#let [g!_ (code.local-symbol "_______")
                   g!input (code.local-symbol "_______input")]
             members (poly.variant (p.many Codec<JSON,?>//encode))]
            (wrap (` (: (~ (@JSON//encode inputT))
                        (function ((~ g!_) (~ g!input))
                          (case (~ g!input)
                            (~+ (list/join (list/map (function (_ [tag g!encode])
                                                       (list (` ((~ (code.nat tag)) (~ g!input)))
                                                             (` (//.json [(~ (code.frac (..tag tag)))
                                                                          ((~ g!encode) (~ g!input))]))))
                                                     (list.enumerate members))))))))))
          (do @
            [g!encoders (poly.tuple (p.many Codec<JSON,?>//encode))
             #let [g!_ (code.local-symbol "_______")
                   g!members (|> (list.size g!encoders) dec
                                 (list.n/range +0)
                                 (list/map (|>> nat/encode code.local-symbol)))]]
            (wrap (` (: (~ (@JSON//encode inputT))
                        (function ((~ g!_) [(~+ g!members)])
                          (//.json [(~+ (list/map (function (_ [g!member g!encode])
                                                    (` ((~ g!encode) (~ g!member))))
                                                  (list.zip2 g!members g!encoders)))]))))))
          ## Type recursion
          (do @
            [[selfC non-recC] (poly.recursive Codec<JSON,?>//encode)
             #let [g! (code.local-symbol "____________")]]
            (wrap (` (: (~ (@JSON//encode inputT))
                        ((~! ..rec-encode) (.function ((~ g!) (~ selfC))
                                             (~ non-recC)))))))
          poly.recursive-self
          ## Type applications
          (do @
            [partsC (poly.apply (p.many Codec<JSON,?>//encode))]
            (wrap (` ((~+ partsC)))))
          ## Polymorphism
          (do @
            [[funcC varsC bodyC] (poly.polymorphic Codec<JSON,?>//encode)]
            (wrap (` (: (All [(~+ varsC)]
                          (-> (~+ (list/map (function (_ varC) (` (->  (~ varC) //.JSON)))
                                            varsC))
                              (-> ((~ (poly.to-code *env* inputT)) (~+ varsC))
                                  //.JSON)))
                        (function ((~ funcC) (~+ varsC))
                          (~ bodyC))))))
          poly.parameter
          poly.recursive-call
          ## If all else fails...
          (p.fail (format "Cannot create JSON encoder for: " (type.to-text inputT)))
          ))))

(poly: Codec<JSON,?>//decode
  (with-expansions
    [<basic> (do-template [<matcher> <decoder>]
               [(do @
                  [_ <matcher>]
                  (wrap (` (: (~ (@JSON//decode inputT))
                              <decoder>))))]

               [(poly.exactly Any)  //.null]
               [(poly.similar Bit)  //.boolean]
               [(poly.similar Nat)  (p.codec (~! ..Codec<JSON,Nat>) //.any)]
               [(poly.similar Int)  (p.codec (~! ..Codec<JSON,Int>) //.any)]
               [(poly.similar Frac) //.number]
               [(poly.similar Text) //.string])
     <time> (do-template [<type> <codec>]
              [(do @
                 [_ (poly.exactly <type>)]
                 (wrap (` (: (~ (@JSON//decode inputT))
                             (p.codec <codec> //.string)))))]

              [du.Duration du.Codec<Text,Duration>]
              ## [i.Instant   i.Codec<Text,Instant>]
              [da.Date     da.Codec<Text,Date>]
              [da.Day      da.Codec<Text,Day>]
              [da.Month    da.Codec<Text,Month>])]
    (do @
      [*env* poly.env
       #let [@JSON//decode (: (-> Type Code)
                              (function (_ type)
                                (` (//.Reader (~ (poly.to-code *env* type))))))]
       inputT poly.peek]
      ($_ p.either
          <basic>
          <time>
          (do @
            [unitT (poly.apply (p.after (poly.exactly unit.Qty)
                                        poly.any))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (p.codec (~! Codec<JSON,Qty>) //.any)))))
          (do @
            [[_ _ valC] (poly.apply ($_ p.seq
                                        (poly.exactly d.Dictionary)
                                        (poly.exactly .Text)
                                        Codec<JSON,?>//decode))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (//.object (~ valC))))))
          (do @
            [[_ subC] (poly.apply (p.seq (poly.exactly .Maybe)
                                         Codec<JSON,?>//decode))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (//.nullable (~ subC))))))
          (do @
            [[_ subC] (poly.apply (p.seq (poly.exactly .List)
                                         Codec<JSON,?>//decode))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (//.array (p.some (~ subC)))))))
          (do @
            [members (poly.variant (p.many Codec<JSON,?>//decode))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        ($_ p.alt
                            (~+ (list/map (function (_ [tag memberC])
                                            (` (|> (~ memberC)
                                                   (p.after (//.number! (~ (code.frac (..tag tag)))))
                                                   //.array)))
                                          (list.enumerate members))))))))
          (do @
            [g!decoders (poly.tuple (p.many Codec<JSON,?>//decode))]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (//.array ($_ p.seq (~+ g!decoders)))))))
          ## Type recursion
          (do @
            [[selfC bodyC] (poly.recursive Codec<JSON,?>//decode)
             #let [g! (code.local-symbol "____________")]]
            (wrap (` (: (~ (@JSON//decode inputT))
                        (p.rec (.function ((~ g!) (~ selfC))
                                 (~ bodyC)))))))
          poly.recursive-self
          ## Type applications
          (do @
            [[funcC argsC] (poly.apply (p.seq Codec<JSON,?>//decode (p.many Codec<JSON,?>//decode)))]
            (wrap (` ((~ funcC) (~+ argsC)))))
          ## Polymorphism
          (do @
            [[funcC varsC bodyC] (poly.polymorphic Codec<JSON,?>//decode)]
            (wrap (` (: (All [(~+ varsC)]
                          (-> (~+ (list/map (|>> (~) //.Reader (`)) varsC))
                              (//.Reader ((~ (poly.to-code *env* inputT)) (~+ varsC)))))
                        (function ((~ funcC) (~+ varsC))
                          (~ bodyC))))))
          poly.parameter
          poly.recursive-call
          ## If all else fails...
          (p.fail (format "Cannot create JSON decoder for: " (type.to-text inputT)))
          ))))

(syntax: #export (Codec<JSON,?> inputT)
  {#.doc (doc "A macro for automatically producing JSON codecs."
              (type: Variant
                (#Case0 Bit)
                (#Case1 Text)
                (#Case2 Frac))

              (type: Record
                {#bit Bit
                 #frac Frac
                 #text Text
                 #maybe (Maybe Frac)
                 #list (List Frac)
                 #variant Variant
                 #tuple [Bit Frac Text]
                 #dict (Dictionary Text Frac)})

              (derived: (Codec<JSON,?> Record)))}
  (with-gensyms [g!inputs]
    (wrap (list (` (: (Codec //.JSON (~ inputT))
                      (structure (def: (~' encode) ((~! Codec<JSON,?>//encode) (~ inputT)))
                                 (def: ((~' decode) (~ g!inputs)) (//.run (~ g!inputs) ((~! Codec<JSON,?>//decode) (~ inputT))))
                                 )))))))