aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/data/format/json.lux
blob: 895a6931fafd8aec5de543bdc00336f63ba0e14d (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
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
(.require
 [library
  [lux (.except has)
   [abstract
    [equivalence (.only Equivalence)]
    [codec (.only Codec)]
    ["[0]" monad (.only do)]]
   [control
    ["<>" parser (.use "[1]#[0]" monad)]
    ["[0]" pipe]
    ["[0]" maybe]
    ["[0]" try (.only Try)]
    [function
     [predicate (.only Predicate)]]]
   [data
    ["[0]" bit]
    ["[0]" product]
    ["[0]" text (.use "[1]#[0]" equivalence monoid)
     ["<[1]>" \\parser (.only Parser)]]
    [collection
     ["[0]" list (.use "[1]#[0]" mix functor)]
     ["[0]" sequence (.only Sequence sequence) (.use "[1]#[0]" monad)]
     ["[0]" dictionary (.only Dictionary)]]]
   [math
    [number
     ["n" nat]
     ["f" frac (.use "[1]#[0]" decimal)]]]
   ["[0]" meta (.only monad)
    ["[0]" code (.only)
     ["<[1]>" \\parser]]
    [macro
     [syntax (.only syntax)]
     ["^" pattern]]]]])

(with_template [<name> <type>]
  [(type .public <name>
     <type>)]

  [Null    Any]
  [Boolean Bit]
  [Number  Frac]
  [String  Text]
  )

(type .public JSON
  (Rec JSON
    (Variant
     {#Null    Null}
     {#Boolean Boolean}
     {#Number  Number}
     {#String  String}
     {#Array   (Sequence JSON)}
     {#Object  (Dictionary String JSON)})))

(with_template [<name> <type>]
  [(type .public <name>
     <type>)]

  [Array  (Sequence JSON)]
  [Object (Dictionary String JSON)]
  )

(def .public null?
  (Predicate JSON)
  (|>> (pipe.case {#Null} true
         _ false)))

(def .public object
  (-> (List [String JSON]) JSON)
  (|>> (dictionary.of_list text.hash) {..#Object}))

(type JSON'
  (Rec JSON'
    (Variant
     {#Null'    Null}
     {#Boolean' Boolean}
     {#Number'  Number}
     {#String'  String}
     {#Array'   (Sequence JSON')}
     {#Object'  (Dictionary String JSON')}
     {#Code'    Code})))

(def jsonP
  (<code>.Parser JSON')
  (<>.rec
   (function (_ jsonP)
     (all <>.or
          (<code>.form (<>#in []))
          <code>.bit
          <code>.frac
          <code>.text
          (<>#each sequence.of_list
                   (<code>.tuple (<>.some jsonP)))
          (<>#each (dictionary.of_list text.hash)
                   (<code>.variant (<>.some (<>.and <code>.text jsonP))))
          <code>.any
          ))))

(def (jsonF token)
  (-> JSON' Code)
  (case token
    {#Null' _}
    (` {..#Null})
    
    (^.with_template [<ctor> <input_tag> <output_tag>]
      [{<input_tag> value}
       (` {<output_tag> (, (<ctor> value))})])
    ([code.bit  ..#Boolean' ..#Boolean]
     [code.frac ..#Number' ..#Number]
     [code.text ..#String' ..#String])
    
    {#Array' members}
    (` {..#Array (sequence.sequence (,* (sequence.list (sequence#each jsonF members))))})

    {#Object' pairs}
    (` {..#Object (dictionary.of_list text.hash
                                      (list (,* (|> pairs
                                                    dictionary.entries
                                                    (list#each (function (_ [key_name value])
                                                                 (` [(, (code.text key_name)) (, (jsonF value))])))))))})

    {#Code' code}
    code))

(def .public json
  (syntax (_ [token ..jsonP])
    (in (list (` (is JSON (, (jsonF token))))))))

(def .public (fields json)
  (-> JSON (Try (List String)))
  (case json
    {#Object obj}
    {try.#Success (dictionary.keys obj)}

    _
    {try.#Failure (all text#composite "Cannot get the fields of a non-object.")}))

(def .public (field key json)
  (-> String JSON (Try JSON))
  (case json
    {#Object obj}
    (case (dictionary.value key obj)
      {.#Some value}
      {try.#Success value}

      {.#None}
      {try.#Failure (all text#composite "Missing field '" key "' on object.")})

    _
    {try.#Failure (all text#composite "Cannot get field '" key "' on a non-object.")}))

(def .public (has key value json)
  (-> String JSON JSON (Try JSON))
  (case json
    {#Object obj}
    {try.#Success {#Object (dictionary.has key value obj)}}

    _
    {try.#Failure (all text#composite "Cannot set field '" key "' on a non-object.")}))

(with_template [<name> <tag> <type>]
  [(def .public (<name> key json)
     (-> Text JSON (Try <type>))
     (case (field key json)
       {try.#Success {<tag> value}}
       {try.#Success value}

       {try.#Success _}
       {try.#Failure (all text#composite "Wrong value type at key: " key)}

       {try.#Failure error}
       {try.#Failure error}))]

  [boolean_field #Boolean Boolean]
  [number_field  #Number  Number]
  [string_field  #String  String]
  [array_field   #Array   Array]
  [object_field  #Object  Object]
  )

(def .public equivalence
  (Equivalence JSON)
  (implementation
   (def (= x y)
     (case [x y]
       [{#Null} {#Null}]
       #1

       (^.with_template [<tag> <struct>]
         [[{<tag> x'} {<tag> y'}]
          (at <struct> = x' y')])
       ([#Boolean bit.equivalence]
        [#Number  f.equivalence]
        [#String  text.equivalence])

       [{#Array xs} {#Array ys}]
       (and (n.= (sequence.size xs) (sequence.size ys))
            (list#mix (function (_ idx prev)
                        (and prev
                             (maybe.else #0
                                         (do maybe.monad
                                           [x' (sequence.item idx xs)
                                            y' (sequence.item idx ys)]
                                           (in (= x' y'))))))
                      #1
                      (list.indices (sequence.size xs))))
       
       [{#Object xs} {#Object ys}]
       (and (n.= (dictionary.size xs) (dictionary.size ys))
            (list#mix (function (_ [xk xv] prev)
                        (and prev
                             (case (dictionary.value xk ys)
                               {.#None}    #0
                               {.#Some yv} (= xv yv))))
                      #1
                      (dictionary.entries xs)))
       
       _
       #0))))

............................................................
............................................................
............................................................

(def (null_format _)
  (-> Null Text)
  "null")

(def boolean_format
  (-> Boolean Text)
  (|>> (pipe.case
         #0 "false"
         #1 "true")))

(def number_format
  (-> Number Text)
  (|>> (pipe.case
         +0.0 ... OR -0.0
         "0.0"

         value
         (let [raw (at f.decimal encoded value)]
           (if (f.< +0.0 value)
             raw
             (|> raw (text.split_at 1) maybe.trusted product.right))))))

(def escape "\")
(def escaped_dq (text#composite ..escape text.double_quote))

(def string_format
  (-> String Text)
  (|>> (text.replaced text.double_quote ..escaped_dq)
       (text.enclosed [text.double_quote text.double_quote])))

(with_template [<token> <name>]
  [(def <name>
     Text
     <token>)]

  ["," value_separator]
  [":" entry_separator]

  ["[" array_start]
  ["]" array_end]

  ["{" object_start]
  ["}" object_end]
  )

(def (array_format format)
  (-> (-> JSON Text) (-> Array Text))
  (|>> (sequence#each format)
       sequence.list
       (text.interposed ..value_separator)
       (text.enclosed [..array_start ..array_end])))

(def (kv_format format [key value])
  (-> (-> JSON Text) (-> [String JSON] Text))
  (all text#composite
       (..string_format key)
       ..entry_separator
       (format value)
       ))

(def (object_format format)
  (-> (-> JSON Text) (-> Object Text))
  (|>> dictionary.entries
       (list#each (..kv_format format))
       (text.interposed ..value_separator)
       (text.enclosed [..object_start ..object_end])))

(def .public (format json)
  (-> JSON Text)
  (case json
    (^.with_template [<tag> <format>]
      [{<tag> value}
       (<format> value)])
    ([#Null    ..null_format]
     [#Boolean ..boolean_format]
     [#Number  ..number_format]
     [#String  ..string_format]
     [#Array   (..array_format format)]
     [#Object  (..object_format format)])
    ))

............................................................
............................................................
............................................................

(def space_parser
  (Parser Text)
  (<text>.some <text>.space))

(def value_separator_parser
  (Parser [Text Any Text])
  (all <>.and
       ..space_parser
       (<text>.this ..value_separator)
       ..space_parser))

(def null_parser
  (Parser Null)
  (do <>.monad
    [_ (<text>.this "null")]
    (in [])))

(with_template [<name> <token> <value>]
  [(def <name>
     (Parser Boolean)
     (do <>.monad
       [_ (<text>.this <token>)]
       (in <value>)))]

  [true_parser  "true"  #1]
  [false_parser "false" #0]
  )

(def boolean_parser
  (Parser Boolean)
  (all <>.either
       ..true_parser
       ..false_parser))

(def number_parser
  (Parser Number)
  (do [! <>.monad]
    [signed? (<>.parses? (<text>.this "-"))
     digits (<text>.many <text>.decimal)
     decimals (<>.else "0"
                       (do !
                         [_ (<text>.this ".")]
                         (<text>.many <text>.decimal)))
     exp (<>.else ""
                  (do !
                    [mark (<text>.one_of "eE")
                     signed?' (<>.parses? (<text>.this "-"))
                     offset (<text>.many <text>.decimal)]
                    (in (all text#composite mark (if signed?' "-" "") offset))))]
    (case (f#decoded (all text#composite (if signed? "-" "") digits "." decimals exp))
      {try.#Failure message}
      (<>.failure message)
      
      {try.#Success value}
      (in value))))

(def escaped_parser
  (Parser Text)
  (all <>.either
       (<>.after (<text>.this "\t")
                 (<>#in text.tab))
       (<>.after (<text>.this "\b")
                 (<>#in text.back_space))
       (<>.after (<text>.this "\n")
                 (<>#in text.new_line))
       (<>.after (<text>.this "\r")
                 (<>#in text.carriage_return))
       (<>.after (<text>.this "\f")
                 (<>#in text.form_feed))
       (<>.after (<text>.this (text#composite "\" text.double_quote))
                 (<>#in text.double_quote))
       (<>.after (<text>.this "\\")
                 (<>#in "\"))))

(def string_parser
  (Parser String)
  (<| (<text>.enclosed [text.double_quote text.double_quote])
      (loop (again [_ []]))
      (do [! <>.monad]
        [chars (<text>.some (<text>.none_of (text#composite "\" text.double_quote)))
         stop <text>.next])
      (if (text#= "\" stop)
        (do !
          [escaped escaped_parser
           next_chars (again [])]
          (in (all text#composite chars escaped next_chars)))
        (in chars))))

(def (kv_parser json_parser)
  (-> (Parser JSON) (Parser [String JSON]))
  (do <>.monad
    [key ..string_parser
     _ ..space_parser
     _ (<text>.this ..entry_separator)
     _ ..space_parser
     value json_parser]
    (in [key value])))

(with_template [<name> <type> <open> <close> <elem_parser> <prep>]
  [(def (<name> json_parser)
     (-> (Parser JSON) (Parser <type>))
     (do <>.monad
       [_ (<text>.this <open>)
        _ space_parser
        elems (<>.separated_by ..value_separator_parser <elem_parser>)
        _ space_parser
        _ (<text>.this <close>)]
       (in (<prep> elems))))]

  [array_parser  Array  ..array_start ..array_end json_parser sequence.of_list]
  [object_parser Object ..object_start ..object_end (kv_parser json_parser) (dictionary.of_list text.hash)]
  )

(def json_parser
  (Parser JSON)
  (<>.rec
   (function (_ json_parser)
     (all <>.or
          null_parser
          boolean_parser
          number_parser
          string_parser
          (array_parser json_parser)
          (object_parser json_parser)))))

(def .public codec
  (Codec Text JSON)
  (implementation
   (def encoded ..format)
   (def decoded (<text>.result json_parser))))