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

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

(def: (rec_encoded non_rec)
  (All (_ a) (-> (-> (-> a JSON)
                     (-> a JSON))
                 (-> a JSON)))
  (function (_ input)
    (non_rec (rec_encoded non_rec) input)))

(def: low_mask Nat (|> 1 (i64.left_shifted 32) --))
(def: high_mask Nat (|> low_mask (i64.left_shifted 32)))

(implementation: nat_codec
  (codec.Codec JSON Nat)
  
  (def: (encoded 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: decoded
    (</>.result (</>.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: encoded
    (|>> .nat (\ nat_codec encoded)))
  (def: decoded
    (|>> (\ nat_codec decoded) (\ try.functor each .int))))

... Builds a JSON generator for potentially inexistent values.
(def: (nullable writer)
  (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: encoded
    (|>> ((debug.private unit.out))
         (\ ..int_codec encoded)))
  (def: decoded
    (|>> (\ ..int_codec decoded)
         (\ try.functor each (debug.private unit.in)))))

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

               [(<type>.exactly Any) (function ((~ g!_) (~ (code.identifier ["" "0"]))) #/.Null)]
               [(<type>.sub Bit)     (|>> #/.Boolean)]
               [(<type>.sub Nat)     (\ (~! ..nat_codec) (~' encoded))]
               [(<type>.sub Int)     (\ (~! ..int_codec) (~' encoded))]
               [(<type>.sub Frac)    (|>> #/.Number)]
               [(<type>.sub Text)    (|>> #/.String)])
     <time> (template [<type> <codec>]
              [(do !
                 [_ (<type>.exactly <type>)]
                 (in (` (: (~ (@JSON\encoded inputT))
                           (|>> (\ (~! <codec>) (~' encoded)) #/.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 [g!_ (code.local_identifier "_______")
             @JSON\encoded (: (-> Type Code)
                              (function (_ type)
                                (` (-> (~ (poly.code *env* type)) /.JSON))))]
       inputT <type>.next]
      ($_ <>.either
          <basic>
          <time>
          (do !
            [unitT (<type>.applied (<>.after (<type>.exactly unit.Qty)
                                             <type>.any))]
            (in (` (: (~ (@JSON\encoded inputT))
                      (\ (~! qty_codec) (~' encoded))))))
          (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)
                                             encoded))]
            (in (` (: (~ (@JSON\encoded inputT))
                      (|>> ((~! dictionary.entries))
                           ((~! list\each) (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)
                                           encoded))]
            (in (` (: (~ (@JSON\encoded inputT))
                      ((~! ..nullable) (~ =sub=))))))
          (do !
            [[_ =sub=] (<type>.applied ($_ <>.and
                                           (<type>.exactly .List)
                                           encoded))]
            (in (` (: (~ (@JSON\encoded inputT))
                      (|>> ((~! list\each) (~ =sub=)) ((~! row.of_list)) #/.Array)))))
          (do !
            [.let [g!_ (code.local_identifier "_______")
                   g!input (code.local_identifier "_______input")]
             members (<type>.variant (<>.many encoded))
             .let [last (-- (list.size members))]]
            (in (` (: (~ (@JSON\encoded inputT))
                      (function ((~ g!_) (~ g!input))
                        (case (~ g!input)
                          (~+ (list\conjoint (list\each (function (_ [tag g!encoded])
                                                          (if (n.= last tag)
                                                            (.list (` ((~ (code.nat (-- tag))) #1 (~ g!input)))
                                                                   (` ((~! /.json) [(~ (code.frac (..tag (-- tag))))
                                                                                    #1
                                                                                    ((~ g!encoded) (~ g!input))])))
                                                            (.list (` ((~ (code.nat tag)) #0 (~ g!input)))
                                                                   (` ((~! /.json) [(~ (code.frac (..tag tag)))
                                                                                    #0
                                                                                    ((~ g!encoded) (~ g!input))])))))
                                                        (list.enumeration members))))))))))
          (do !
            [g!encoders (<type>.tuple (<>.many encoded))
             .let [g!_ (code.local_identifier "_______")
                   g!members (|> (list.size g!encoders)
                                 list.indices
                                 (list\each (|>> n\encoded code.local_identifier)))]]
            (in (` (: (~ (@JSON\encoded inputT))
                      (function ((~ g!_) [(~+ g!members)])
                        ((~! /.json) [(~+ (list\each (function (_ [g!member g!encoded])
                                                       (` ((~ g!encoded) (~ g!member))))
                                                     (list.zipped/2 g!members g!encoders)))]))))))
          ... Type recursion
          (do !
            [[selfC non_recC] (<type>.recursive encoded)
             .let [g! (code.local_identifier "____________")]]
            (in (` (: (~ (@JSON\encoded inputT))
                      ((~! ..rec_encoded) (.function ((~ g!) (~ selfC))
                                            (~ non_recC)))))))
          <type>.recursive_self
          ... Type applications
          (do !
            [partsC (<type>.applied (<>.many encoded))]
            (in (` ((~+ partsC)))))
          ... Polymorphism
          (do !
            [[funcC varsC bodyC] (<type>.polymorphic encoded)]
            (in (` (: (All ((~ g!_) (~+ varsC))
                        (-> (~+ (list\each (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: decoded
  (with_expansions
    [<basic> (template [<matcher> <decoder>]
               [(do !
                  [_ <matcher>]
                  (in (` (: (~ (@JSON\decoded 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\decoded 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 [g!_ (code.local_identifier "_______")
             @JSON\decoded (: (-> Type Code)
                              (function (_ type)
                                (` (</>.Parser (~ (poly.code *env* type))))))]
       inputT <type>.next]
      ($_ <>.either
          <basic>
          <time>
          (do !
            [unitT (<type>.applied (<>.after (<type>.exactly unit.Qty)
                                             <type>.any))]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! <>.codec) (~! qty_codec) (~! </>.any))))))
          (do !
            [[_ _ valC] (<type>.applied ($_ <>.and
                                            (<type>.exactly dictionary.Dictionary)
                                            (<type>.exactly .Text)
                                            decoded))]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! </>.dictionary) (~ valC))))))
          (do !
            [[_ subC] (<type>.applied (<>.and (<type>.exactly .Maybe)
                                              decoded))]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! </>.nullable) (~ subC))))))
          (do !
            [[_ subC] (<type>.applied (<>.and (<type>.exactly .List)
                                              decoded))]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! </>.array) ((~! <>.some) (~ subC)))))))
          (do !
            [members (<type>.variant (<>.many decoded))
             .let [last (-- (list.size members))]]
            (in (` (: (~ (@JSON\decoded inputT))
                      ($_ ((~! <>.or))
                          (~+ (list\each (function (_ [tag memberC])
                                           (if (n.= last tag)
                                             (` (|> (~ memberC)
                                                    ((~! <>.after) ((~! </>.boolean!) (~ (code.bit #1))))
                                                    ((~! <>.after) ((~! </>.number!) (~ (code.frac (..tag (-- tag))))))
                                                    ((~! </>.array))))
                                             (` (|> (~ memberC)
                                                    ((~! <>.after) ((~! </>.boolean!) (~ (code.bit #0))))
                                                    ((~! <>.after) ((~! </>.number!) (~ (code.frac (..tag tag)))))
                                                    ((~! </>.array))))))
                                         (list.enumeration members))))))))
          (do !
            [g!decoders (<type>.tuple (<>.many decoded))]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! </>.array) ($_ ((~! <>.and)) (~+ g!decoders)))))))
          ... Type recursion
          (do !
            [[selfC bodyC] (<type>.recursive decoded)
             .let [g! (code.local_identifier "____________")]]
            (in (` (: (~ (@JSON\decoded inputT))
                      ((~! <>.rec) (.function ((~ g!) (~ selfC))
                                     (~ bodyC)))))))
          <type>.recursive_self
          ... Type applications
          (do !
            [[funcC argsC] (<type>.applied (<>.and decoded (<>.many decoded)))]
            (in (` ((~ funcC) (~+ argsC)))))
          ... Polymorphism
          (do !
            [[funcC varsC bodyC] (<type>.polymorphic decoded)]
            (in (` (: (All ((~ g!_) (~+ varsC))
                        (-> (~+ (list\each (|>> (~) </>.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: .public (codec [inputT <code>.any])
  (in (.list (` (: (codec.Codec /.JSON (~ inputT))
                   (implementation
                    (def: (~' encoded)
                      ((~! ..encoded) (~ inputT)))
                    (def: (~' decoded)
                      ((~! </>.result) ((~! ..decoded) (~ inputT))))
                    ))))))