aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/format/json.lux
blob: 379e3b23b64562aa3bd6433c46f430cd19d47ad3 (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
(;module: {#;doc "Functionality for generating and processing values in the JSON format.

                  For more information, please see: http://www.json.org/"}
  lux
  (lux (control functor
                applicative
                ["M" monad #+ do Monad]
                [eq #+ Eq]
                codec
                ["p" parser "p/" Monad<Parser>])
       (data [bool]
             [text "text/" Eq<Text> Monoid<Text>]
             (text ["l" lexer])
             [number "real/" Codec<Text,Real> "nat/" Codec<Text,Nat>]
             maybe
             ["R" result]
             [sum]
             [product]
             (coll [list "L/" Fold<List> Monad<List>]
                   [vector #+ Vector vector "Vector/" Monad<Vector>]
                   ["d" dict]))
       [macro #+ Monad<Lux> with-gensyms]
       (macro ["s" syntax #+ syntax:]
              [code]
              [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  (d;Dict String JSON)))

(do-template [<name> <type>]
  [(type: #export <name> <type>)]

  [Array   (Vector JSON)]
  [Object  (d;Dict String JSON)]
  )

(type: #export (Reader a)
  {#;doc "JSON reader."}
  (p;Parser (List JSON) a))

## [Syntax]
(syntax: #export (json token)
  {#;doc (doc "A simple way to produce JSON literals."
              (json true)
              (json 123.456)
              (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))))))))
      ([#;Bool code;bool            #Boolean]
       [#;Real code;real            #Number]
       [#;Text code;text            #String])

      [_ (#;Tag ["" "null"])]
      (wrap (list (` (: JSON #Null))))

      [_ (#;Tuple members)]
      (wrap (list (` (: JSON (#Array (vector (~@ (L/map wrapper members))))))))

      [_ (#;Record pairs)]
      (do Monad<Lux>
        [pairs' (M;map @
                       (function [[slot value]]
                         (case slot
                           [_ (#;Text key-name)]
                           (wrap (` [(~ (code;text key-name)) (~ (wrapper value))]))

                           _
                           (macro;fail "Wrong syntax for JSON object.")))
                       pairs)]
        (wrap (list (` (: JSON (#Object (d;from-list text;Hash<Text> (list (~@ pairs')))))))))
      
      _
      (wrap (list token))
      )))

(def: #export null
  {#;doc "The null JSON value."}
  JSON
  #Null)

(def: #export (fields json)
  {#;doc "Get all the fields in a JSON object."}
  (-> JSON (R;Result (List String)))
  (case json
    (#Object obj)
    (#R;Success (d;keys obj))

    _
    (#R;Error ($_ text/append "Cannot get the fields of a non-object."))))

(def: #export (get key json)
  {#;doc "A JSON object field getter."}
  (-> String JSON (R;Result JSON))
  (case json
    (#Object obj)
    (case (d;get key obj)
      (#;Some value)
      (#R;Success value)

      #;None
      (#R;Error ($_ text/append "Missing field \"" key "\" on object.")))

    _
    (#R;Error ($_ text/append "Cannot get field \"" key "\" of a non-object."))))

(def: #export (set key value json)
  {#;doc "A JSON object field setter."}
  (-> String JSON JSON (R;Result JSON))
  (case json
    (#Object obj)
    (#R;Success (#Object (d;put key value obj)))

    _
    (#R;Error ($_ text/append "Cannot set field \"" key "\" of a non-object."))))

(do-template [<name> <tag> <type> <desc>]
  [(def: #export (<name> key json)
     {#;doc (#;TextA ($_ text/append "A JSON object field getter for " <desc> "."))}
     (-> Text JSON (R;Result <type>))
     (case (get key json)
       (#R;Success (<tag> value))
       (#R;Success value)

       (#R;Success _)
       (#R;Error ($_ text/append "Wrong value type at key: " key))

       (#R;Error error)
       (#R;Error 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 ($_ text/append "A JSON generator for " <desc> "."))}
     (-> <type> JSON)
     (<tag> value))]

  [boolean Boolean #Boolean "booleans"]
  [number  Number  #Number  "numbers"]
  [string  String  #String  "strings"]
  [array   Array   #Array   "arrays"]
  [object  Object  #Object  "objects"]
  )

(def: #export (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))))

(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))
           (L/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.= (d;size xs) (d;size ys))
           (L/fold (function [[xk xv] prev]
                     (and prev
                          (case (d;get xk ys)
                            #;None   false
                            (#;Some yv) (= xv yv))))
                   true
                   (d;entries xs)))
      
      _
      false)))