aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/poly/lux/data/format/json.lux
blob: c4cae2881ee423b89a2f5a46fe193061d2f955a8 (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
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
(.module:
  {#.doc "Codecs for values in the JSON format."}
  [library
   [lux #*
    ["." debug]
    [abstract
     [monad (#+ do)]
     ["." codec]]
    [control
     ["." try]
     ["<>" parser
      ["<.>" type]
      ["</>" json]]]
    [data
     ["." text
      ["%" format (#+ format)]]
     [collection
      ["." list ("#\." monad)]
      ["." row (#+ row)]
      ["." dictionary]]]
    [macro
     [syntax (#+ syntax:)]
     ["." code]
     ["." poly (#+ poly:)]]
    [math
     [number
      ["n" nat ("#\." decimal)]
      ["." i64]
      ["." int]
      ["." frac]]]
    [time
     ## ["." instant]
     ## ["." duration]
     ["." date]
     ["." day]
     ["." month]]
    ["." type
     ["." unit]]]]
  [\\library
   ["." / (#+ JSON)]])

(def: tag
  (-> Nat Frac)
  (|>> .int int.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_shifted 32) dec))
(def: high_mask Nat (|> low_mask (i64.left_shifted 32)))

(implementation: nat_codec
  (codec.Codec JSON Nat)
  
  (def: (encode input)
    (let [high (|> input (i64.and high_mask) (i64.right_shifted 32))
          low (i64.and low_mask input)]
      (#/.Array (row (|> high .int int.frac #/.Number)
                     (|> low .int int.frac #/.Number)))))
  (def: decode
    (</>.run (</>.array
              (do <>.monad
                [high </>.number
                 low </>.number]
                (in (n.+ (|> high frac.int .nat (i64.left_shifted 32))
                         (|> low frac.int .nat))))))))

(implementation: int_codec
  (codec.Codec JSON Int)
  
  (def: encode (|>> .nat (\ nat_codec encode)))
  (def: decode
    (|>> (\ nat_codec decode) (\ try.functor 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))))

(implementation: qty_codec
  (All [unit]
    (codec.Codec JSON (unit.Qty unit)))
  
  (def: encode
    (|>> ((debug.private unit.out))
         (\ ..int_codec encode)))
  (def: decode
    (|>> (\ ..int_codec decode)
         (\ try.functor map (debug.private unit.in)))))

(poly: encode
  (with_expansions
    [<basic> (template [<matcher> <encoder>]
               [(do !
                  [.let [g!_ (code.local_identifier "_______")]
                   _ <matcher>]
                  (in (` (: (~ (@JSON\encode inputT))
                            <encoder>))))]

               [(<type>.exactly Any) (function ((~ g!_) (~ (code.identifier ["" "0"]))) #/.Null)]
               [(<type>.sub Bit)     (|>> #/.Boolean)]
               [(<type>.sub Nat)     (\ (~! ..nat_codec) (~' encode))]
               [(<type>.sub Int)     (\ (~! ..int_codec) (~' encode))]
               [(<type>.sub Frac)    (|>> #/.Number)]
               [(<type>.sub Text)    (|>> #/.String)])
     <time> (template [<type> <codec>]
              [(do !
                 [_ (<type>.exactly <type>)]
                 (in (` (: (~ (@JSON\encode inputT))
                           (|>> (\ (~! <codec>) (~' encode)) #/.String)))))]

              ## [duration.Duration duration.codec]
              ## [instant.Instant instant.codec]
              [date.Date date.codec]
              [day.Day day.codec]
              [month.Month month.codec])]
    (do {! <>.monad}
      [*env* <type>.env
       .let [@JSON\encode (: (-> Type Code)
                             (function (_ type)
                               (` (-> (~ (poly.code *env* type)) /.JSON))))]
       inputT <type>.peek]
      ($_ <>.either
          <basic>
          <time>
          (do !
            [unitT (<type>.applied (<>.after (<type>.exactly unit.Qty)
                                             <type>.any))]
            (in (` (: (~ (@JSON\encode inputT))
                      (\ (~! qty_codec) (~' encode))))))
          (do !
            [.let [g!_ (code.local_identifier "_______")
                   g!key (code.local_identifier "_______key")
                   g!val (code.local_identifier "_______val")]
             [_ _ =val=] (<type>.applied ($_ <>.and
                                             (<type>.exactly dictionary.Dictionary)
                                             (<type>.exactly .Text)
                                             encode))]
            (in (` (: (~ (@JSON\encode inputT))
                      (|>> ((~! dictionary.entries))
                           ((~! list\map) (function ((~ g!_) [(~ g!key) (~ g!val)])
                                            [(~ g!key) ((~ =val=) (~ g!val))]))
                           ((~! dictionary.of_list) (~! text.hash))
                           #/.Object)))))
          (do !
            [[_ =sub=] (<type>.applied ($_ <>.and
                                           (<type>.exactly .Maybe)
                                           encode))]
            (in (` (: (~ (@JSON\encode inputT))
                      ((~! ..nullable) (~ =sub=))))))
          (do !
            [[_ =sub=] (<type>.applied ($_ <>.and
                                           (<type>.exactly .List)
                                           encode))]
            (in (` (: (~ (@JSON\encode inputT))
                      (|>> ((~! list\map) (~ =sub=)) ((~! row.of_list)) #/.Array)))))
          (do !
            [.let [g!_ (code.local_identifier "_______")
                   g!input (code.local_identifier "_______input")]
             members (<type>.variant (<>.many encode))
             .let [last (dec (list.size members))]]
            (in (` (: (~ (@JSON\encode inputT))
                      (function ((~ g!_) (~ g!input))
                        (case (~ g!input)
                          (~+ (list\join (list\map (function (_ [tag g!encode])
                                                     (if (n.= last tag)
                                                       (.list (` ((~ (code.nat (dec tag))) #1 (~ g!input)))
                                                              (` ((~! /.json) [(~ (code.frac (..tag (dec tag))))
                                                                               #1
                                                                               ((~ g!encode) (~ g!input))])))
                                                       (.list (` ((~ (code.nat tag)) #0 (~ g!input)))
                                                              (` ((~! /.json) [(~ (code.frac (..tag tag)))
                                                                               #0
                                                                               ((~ g!encode) (~ g!input))])))))
                                                   (list.enumeration members))))))))))
          (do !
            [g!encoders (<type>.tuple (<>.many encode))
             .let [g!_ (code.local_identifier "_______")
                   g!members (|> (list.size g!encoders)
                                 list.indices
                                 (list\map (|>> n\encode code.local_identifier)))]]
            (in (` (: (~ (@JSON\encode inputT))
                      (function ((~ g!_) [(~+ g!members)])
                        ((~! /.json) [(~+ (list\map (function (_ [g!member g!encode])
                                                      (` ((~ g!encode) (~ g!member))))
                                                    (list.zipped/2 g!members g!encoders)))]))))))
          ## Type recursion
          (do !
            [[selfC non_recC] (<type>.recursive encode)
             .let [g! (code.local_identifier "____________")]]
            (in (` (: (~ (@JSON\encode inputT))
                      ((~! ..rec_encode) (.function ((~ g!) (~ selfC))
                                           (~ non_recC)))))))
          <type>.recursive_self
          ## Type applications
          (do !
            [partsC (<type>.applied (<>.many encode))]
            (in (` ((~+ partsC)))))
          ## Polymorphism
          (do !
            [[funcC varsC bodyC] (<type>.polymorphic encode)]
            (in (` (: (All [(~+ varsC)]
                        (-> (~+ (list\map (function (_ varC) (` (-> (~ varC) /.JSON)))
                                          varsC))
                            (-> ((~ (poly.code *env* inputT)) (~+ varsC))
                                /.JSON)))
                      (function ((~ funcC) (~+ varsC))
                        (~ bodyC))))))
          <type>.parameter
          <type>.recursive_call
          ## If all else fails...
          (<>.failure (format "Cannot create JSON encoder for: " (type.format inputT)))
          ))))

(poly: decode
  (with_expansions
    [<basic> (template [<matcher> <decoder>]
               [(do !
                  [_ <matcher>]
                  (in (` (: (~ (@JSON\decode inputT))
                            (~! <decoder>)))))]

               [(<type>.exactly Any)  </>.null]
               [(<type>.sub Bit)      </>.boolean]
               [(<type>.sub Nat)      (<>.codec ..nat_codec </>.any)]
               [(<type>.sub Int)      (<>.codec ..int_codec </>.any)]
               [(<type>.sub Frac)     </>.number]
               [(<type>.sub Text)     </>.string])
     <time> (template [<type> <codec>]
              [(do !
                 [_ (<type>.exactly <type>)]
                 (in (` (: (~ (@JSON\decode inputT))
                           ((~! <>.codec) (~! <codec>) (~! </>.string))))))]

              ## [duration.Duration duration.codec]
              ## [instant.Instant instant.codec]
              [date.Date date.codec]
              [day.Day day.codec]
              [month.Month month.codec])]
    (do {! <>.monad}
      [*env* <type>.env
       .let [@JSON\decode (: (-> Type Code)
                             (function (_ type)
                               (` (</>.Parser (~ (poly.code *env* type))))))]
       inputT <type>.peek]
      ($_ <>.either
          <basic>
          <time>
          (do !
            [unitT (<type>.applied (<>.after (<type>.exactly unit.Qty)
                                             <type>.any))]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! <>.codec) (~! qty_codec) (~! </>.any))))))
          (do !
            [[_ _ valC] (<type>.applied ($_ <>.and
                                            (<type>.exactly dictionary.Dictionary)
                                            (<type>.exactly .Text)
                                            decode))]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! </>.dictionary) (~ valC))))))
          (do !
            [[_ subC] (<type>.applied (<>.and (<type>.exactly .Maybe)
                                              decode))]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! </>.nullable) (~ subC))))))
          (do !
            [[_ subC] (<type>.applied (<>.and (<type>.exactly .List)
                                              decode))]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! </>.array) ((~! <>.some) (~ subC)))))))
          (do !
            [members (<type>.variant (<>.many decode))
             .let [last (dec (list.size members))]]
            (in (` (: (~ (@JSON\decode inputT))
                      ($_ ((~! <>.or))
                          (~+ (list\map (function (_ [tag memberC])
                                          (if (n.= last tag)
                                            (` (|> (~ memberC)
                                                   ((~! <>.after) ((~! </>.boolean!) (~ (code.bit #1))))
                                                   ((~! <>.after) ((~! </>.number!) (~ (code.frac (..tag (dec tag))))))
                                                   ((~! </>.array))))
                                            (` (|> (~ memberC)
                                                   ((~! <>.after) ((~! </>.boolean!) (~ (code.bit #0))))
                                                   ((~! <>.after) ((~! </>.number!) (~ (code.frac (..tag tag)))))
                                                   ((~! </>.array))))))
                                        (list.enumeration members))))))))
          (do !
            [g!decoders (<type>.tuple (<>.many decode))]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! </>.array) ($_ ((~! <>.and)) (~+ g!decoders)))))))
          ## Type recursion
          (do !
            [[selfC bodyC] (<type>.recursive decode)
             .let [g! (code.local_identifier "____________")]]
            (in (` (: (~ (@JSON\decode inputT))
                      ((~! <>.rec) (.function ((~ g!) (~ selfC))
                                     (~ bodyC)))))))
          <type>.recursive_self
          ## Type applications
          (do !
            [[funcC argsC] (<type>.applied (<>.and decode (<>.many decode)))]
            (in (` ((~ funcC) (~+ argsC)))))
          ## Polymorphism
          (do !
            [[funcC varsC bodyC] (<type>.polymorphic decode)]
            (in (` (: (All [(~+ varsC)]
                        (-> (~+ (list\map (|>> (~) </>.Parser (`)) varsC))
                            (</>.Parser ((~ (poly.code *env* inputT)) (~+ varsC)))))
                      (function ((~ funcC) (~+ varsC))
                        (~ bodyC))))))
          <type>.parameter
          <type>.recursive_call
          ## If all else fails...
          (<>.failure (format "Cannot create JSON decoder for: " (type.format inputT)))
          ))))

(syntax: #export (codec inputT)
  {#.doc (doc "A macro for automatically producing JSON codecs."
              (type: Variant
                (#Bit Bit)
                (#Text Text)
                (#Frac Frac))

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

              (derived: (..codec Record)))}
  (in (.list (` (: (codec.Codec /.JSON (~ inputT))
                   (implementation
                    (def: (~' encode)
                      ((~! ..encode) (~ inputT)))
                    (def: (~' decode)
                      ((~! </>.run) ((~! ..decode) (~ inputT))))
                    ))))))