aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/format/xml.lux
blob: 512438c565a80f6ec03524a8fa906aa43ec8ed8f (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
(.module:
  [lux #*
   [abstract
    [monad (#+ do)]
    [equivalence (#+ Equivalence)]
    [codec (#+ Codec)]]
   [control
    [try (#+ Try)]
    ["<>" parser ("#\." monad)
     ["<.>" text (#+ Parser)]]]
   [data
    ["." product]
    ["." name ("#\." equivalence codec)]
    [number
     ["n" nat]
     ["." int]]
    ["." text ("#\." equivalence monoid)]
    [collection
     ["." list ("#\." functor)]
     ["." dictionary (#+ Dictionary)]]]])

(type: #export Tag
  Name)

(type: #export Attribute
  Name)

(type: #export Attrs
  (Dictionary Attribute Text))

(def: #export attributes
  Attrs
  (dictionary.new name.hash))

(type: #export #rec XML
  (#Text Text)
  (#Node Tag Attrs (List XML)))

(def: namespace-separator
  ":")

(def: xml-standard-escape-char^
  (Parser Text)
  ($_ <>.either
      (<>.after (<text>.this "&lt;") (<>\wrap "<"))
      (<>.after (<text>.this "&gt;") (<>\wrap ">"))
      (<>.after (<text>.this "&amp;") (<>\wrap "&"))
      (<>.after (<text>.this "&apos;") (<>\wrap "'"))
      (<>.after (<text>.this "&quot;") (<>\wrap text.double-quote))
      ))

(def: xml-unicode-escape-char^
  (Parser Text)
  (|> (do <>.monad
        [hex? (<>.maybe (<text>.this "x"))
         code (case hex?
                #.None
                (<>.codec int.decimal (<text>.many <text>.decimal))

                (#.Some _)
                (<>.codec int.decimal (<text>.many <text>.hexadecimal)))]
        (wrap (|> code .nat text.from-code)))
      (<>.before (<text>.this ";"))
      (<>.after (<text>.this "&#"))))

(def: xml-escape-char^
  (Parser Text)
  (<>.either xml-standard-escape-char^
             xml-unicode-escape-char^))

(def: xml-char^
  (Parser Text)
  (<>.either (<text>.none-of ($_ text\compose "<>&'" text.double-quote))
             xml-escape-char^))

(def: xml-identifier
  (Parser Text)
  (do <>.monad
    [head (<>.either (<text>.one-of "_")
                     <text>.alpha)
     tail (<text>.some (<>.either (<text>.one-of "_.-")
                                  <text>.alpha-num))]
    (wrap ($_ text\compose head tail))))

(def: namespaced-symbol^
  (Parser Name)
  (do <>.monad
    [first-part xml-identifier
     ?second-part (<| <>.maybe (<>.after (<text>.this ..namespace-separator)) xml-identifier)]
    (case ?second-part
      #.None
      (wrap ["" first-part])

      (#.Some second-part)
      (wrap [first-part second-part]))))

(def: tag^ namespaced-symbol^)
(def: attr-name^ namespaced-symbol^)

(def: spaced^
  (All [a] (-> (Parser a) (Parser a)))
  (let [white-space^ (<>.some <text>.space)]
    (|>> (<>.before white-space^)
         (<>.after white-space^))))

(def: attr-value^
  (Parser Text)
  (let [value^ (<text>.some xml-char^)]
    (<>.either (<text>.enclosed [text.double-quote text.double-quote] value^)
               (<text>.enclosed ["'" "'"] value^))))

(def: attrs^
  (Parser Attrs)
  (<| (:: <>.monad map (dictionary.from-list name.hash))
      <>.some
      (<>.and (spaced^ attr-name^))
      (<>.after (<text>.this "="))
      (spaced^ attr-value^)))

(def: (close-tag^ expected)
  (-> Tag (Parser []))
  (do <>.monad
    [actual (|> tag^
                spaced^
                (<>.after (<text>.this "/"))
                (<text>.enclosed ["<" ">"]))]
    (<>.assert ($_ text\compose "Close tag does not match open tag." text.new-line
                   "Expected: " (name\encode expected) text.new-line
                   "  Actual: " (name\encode actual) text.new-line)
               (name\= expected actual))))

(def: comment^
  (Parser Text)
  (|> (<text>.not (<text>.this "--"))
      <text>.some
      (<text>.enclosed ["<--" "-->"])
      spaced^))

(def: xml-header^
  (Parser Attrs)
  (|> (spaced^ attrs^)
      (<>.before (<text>.this "?>"))
      (<>.after (<text>.this "<?xml"))
      spaced^))

(def: cdata^
  (Parser Text)
  (let [end (<text>.this "]]>")]
    (|> (<text>.some (<text>.not end))
        (<>.after end)
        (<>.after (<text>.this "<![CDATA["))
        spaced^)))

(def: text^
  (Parser XML)
  (|> (<>.either cdata^
                 (<text>.many xml-char^))
      (<>\map (|>> #Text))))

(def: xml^
  (Parser XML)
  (|> (<>.rec
       (function (_ node^)
         (<>.either text^
                    (spaced^
                     (do <>.monad
                       [_ (<text>.this "<")
                        tag (spaced^ tag^)
                        attrs (spaced^ attrs^)
                        #let [no-children^ (do <>.monad
                                             [_ (<text>.this "/>")]
                                             (wrap (#Node tag attrs (list))))
                              with-children^ (do <>.monad
                                               [_ (<text>.this ">")
                                                children (<>.some node^)
                                                _ (close-tag^ tag)]
                                               (wrap (#Node tag attrs children)))]]
                       (<>.either no-children^
                                  with-children^))))))
      ## This is put outside of the call to "rec" because comments
      ## cannot be located inside of XML nodes.
      ## This way, the comments can only be before or after the main document.
      (<>.before (<>.some comment^))
      (<>.after (<>.some comment^))
      (<>.after (<>.maybe xml-header^))))

(def: read
  (-> Text (Try XML))
  (<text>.run xml^))

(def: (sanitize-value input)
  (-> Text Text)
  (|> input
      (text.replace-all "&" "&amp;")
      (text.replace-all "<" "&lt;")
      (text.replace-all ">" "&gt;")
      (text.replace-all "'" "&apos;")
      (text.replace-all text.double-quote "&quot;")))

(def: #export (tag [namespace name])
  (-> Tag Text)
  (case namespace
    "" name
    _ ($_ text\compose namespace ..namespace-separator name)))

(def: #export attribute
  (-> Attribute Text)
  ..tag)

(def: (write-attrs attrs)
  (-> Attrs Text)
  (|> attrs
      dictionary.entries
      (list\map (function (_ [key value])
                  ($_ text\compose (..attribute key) "=" text.double-quote (sanitize-value value) text.double-quote)))
      (text.join-with " ")))

(def: xml-header
  Text
  ($_ text\compose "<?xml version=" text.double-quote "1.0" text.double-quote " encoding=" text.double-quote "UTF-8" text.double-quote "?>"))

(def: (write input)
  (-> XML Text)
  ($_ text\compose xml-header
      (loop [input input]
        (case input
          (#Text value)
          (sanitize-value value)
          
          (#Node xml-tag xml-attrs xml-children)
          (let [tag (..tag xml-tag)
                attrs (if (dictionary.empty? xml-attrs)
                        ""
                        ($_ text\compose " " (write-attrs xml-attrs)))]
            (if (list.empty? xml-children)
              ($_ text\compose "<" tag attrs "/>")
              ($_ text\compose "<" tag attrs ">"
                  (|> xml-children
                      (list\map recur)
                      (text.join-with ""))
                  "</" tag ">")))))))

(structure: #export codec
  (Codec Text XML)
  
  (def: encode ..write)
  (def: decode ..read))

(structure: #export equivalence
  (Equivalence XML)
  
  (def: (= reference sample)
    (case [reference sample]
      [(#Text reference/value) (#Text sample/value)]
      (text\= reference/value sample/value)

      [(#Node reference/tag reference/attrs reference/children)
       (#Node sample/tag sample/attrs sample/children)]
      (and (name\= reference/tag sample/tag)
           (:: (dictionary.equivalence text.equivalence) = reference/attrs sample/attrs)
           (n.= (list.size reference/children)
                (list.size sample/children))
           (|> (list.zip/2 reference/children sample/children)
               (list.every? (product.uncurry =))))

      _
      false)))