-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonParser.hs
293 lines (266 loc) · 7.25 KB
/
JsonParser.hs
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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
module JsonParser where
import qualified Applicative as A
import Core
import qualified Functor as F
import JsonValue
import List (Chars, FilePath, List (..))
import qualified List as L
import qualified Monad as M
import qualified MoreParser as MP
import Optional (Optional (..))
import Parser (ParseResult (..), Parser (..))
import qualified Parser as P
-- $setup
-- >>> :set -XOverloadedStrings
-- A special character is one of the following:
-- * \b Backspace (ascii code 08)
-- * \f Form feed (ascii code 0C)
-- * \n New line
-- * \r Carriage return
-- * \t Tab
-- * \v Vertical tab
-- * \' Apostrophe or single quote (only valid in single quoted json strings)
-- * \" Double quote (only valid in double quoted json strings)
-- * \\ Backslash character
-- https://www.json.org/json-en.html
data SpecialCharacter
= BackSpace
| FormFeed
| NewLine
| CarriageReturn
| Tab
| VerticalTab
| SingleQuote
| DoubleQuote
| Backslash
deriving stock (Eq, Ord, Show)
-- NOTE: This is not inverse to @toSpecialCharacter@.
fromSpecialCharacter ::
SpecialCharacter ->
Char
fromSpecialCharacter BackSpace =
chr 0x08
fromSpecialCharacter FormFeed =
chr 0x0C
fromSpecialCharacter NewLine =
'\n'
fromSpecialCharacter CarriageReturn =
'\r'
fromSpecialCharacter Tab =
'\t'
fromSpecialCharacter VerticalTab =
'\v'
fromSpecialCharacter SingleQuote =
'\''
fromSpecialCharacter DoubleQuote =
'"'
fromSpecialCharacter Backslash =
'\\'
-- NOTE: This is not inverse to @fromSpecialCharacter@.
toSpecialCharacter ::
Char ->
Optional SpecialCharacter
toSpecialCharacter c =
let table =
('b', BackSpace)
:. ('f', FormFeed)
:. ('n', NewLine)
:. ('r', CarriageReturn)
:. ('t', Tab)
:. ('v', VerticalTab)
:. ('\'', SingleQuote)
:. ('"', DoubleQuote)
:. ('\\', Backslash)
:. Nil
in snd F.<$> L.find ((==) c . fst) table
specialCharacterParser :: Parser Char
specialCharacterParser =
P.character M.>>= \c ->
if c == 'u'
then MP.hex
else case toSpecialCharacter c of
Full x -> P.valueParser (fromSpecialCharacter x)
_ -> P.constantParser (UnexpectedChar c)
-- | Parse a JSON string. Handle double-quotes, special characters, hexadecimal characters. See http://json.org for the full list of control characters in JSON.
--
-- /Tip:/ Use `hex`, `fromSpecialCharacter`, `between`, `is`, `charTok`, `toSpecialCharacter`.
--
-- >>> parse jsonString "\" abc\""
-- Result >< " abc"
--
-- >>> parse jsonString "\" abc\" "
-- Result >< " abc"
--
-- >>> parse jsonString "\"abc\"def"
-- Result >def< "abc"
--
-- >>> parse jsonString "\"\\babc\"def"
-- Result >def< "\babc"
--
-- >>> parse jsonString "\"\\u00abc\"def"
-- Result >def< "\171c"
--
-- >>> parse jsonString "\"\\u00ffabc\"def"
-- Result >def< "\255abc"
--
-- >>> parse jsonString "\"\\u00faabc\"def"
-- Result >def< "\250abc"
--
-- >>> isErrorResult (parse jsonString "abc")
-- True
--
-- >>> isErrorResult (parse jsonString "\"\\abc\"def")
-- True
jsonString :: Parser Chars
jsonString = MP.between (P.is '"') (P.is '"') (P.list ch)
where
ch =
P.satisfy (/= '"') M.>>= \c ->
if c == '\\'
then specialCharacterParser
else P.valueParser c
-- | Parse a JSON rational.
--
-- /Tip:/ Use @readFloats@.
--
-- /Optional:/ As an extra challenge, you may wish to support exponential notation
-- as defined on http://json.org/
-- This is not required.
--
-- >>> parse jsonNumber "234"
-- Result >< 234 % 1
--
-- >>> parse jsonNumber "234 "
-- Result >< 234 % 1
--
-- >>> parse jsonNumber "-234"
-- Result >< (-234) % 1
--
-- >>> parse jsonNumber "123.45"
-- Result >< 2469 % 20
--
-- >>> parse jsonNumber "-123"
-- Result >< (-123) % 1
--
-- >>> parse jsonNumber "-123.45"
-- Result >< (-2469) % 20
--
-- >>> isErrorResult (parse jsonNumber "-")
-- True
--
-- >>> isErrorResult (parse jsonNumber "abc")
-- True
jsonNumber :: Parser Rational
jsonNumber = P $ \s ->
case L.readFloats s of
Full (n, rest) -> Result rest n
_ -> UnexpectedString s
-- | Parse a JSON true literal.
--
-- /Tip:/ Use `stringTok`.
--
-- >>> parse jsonTrue "true"
-- Result >< "true"
--
-- >>> isErrorResult (parse jsonTrue "TRUE")
-- True
jsonTrue :: Parser Chars
jsonTrue = MP.string "true"
-- | Parse a JSON false literal.
--
-- /Tip:/ Use `stringTok`.
--
-- >>> parse jsonFalse "false"
-- Result >< "false"
--
-- >>> isErrorResult (parse jsonFalse "FALSE")
-- True
jsonFalse :: Parser Chars
jsonFalse = MP.string "false"
-- | Parse a JSON null literal.
--
-- /Tip:/ Use `stringTok`.
--
-- >>> parse jsonNull "null"
-- Result >< "null"
--
-- >>> isErrorResult (parse jsonNull "NULL")
-- True
jsonNull :: Parser Chars
jsonNull = MP.string "null"
-- | Parse a JSON array.
--
-- /Tip:/ Use `betweenSepbyComma` and `jsonValue`.
--
-- >>> parse jsonArray "[]"
-- Result >< []
--
-- >>> parse jsonArray "[true]"
-- Result >< [JsonTrue]
--
-- >>> parse jsonArray "[true, \"abc\"]"
-- Result >< [JsonTrue,JsonString "abc"]
--
-- >>> parse jsonArray "[true, \"abc\", []]"
-- Result >< [JsonTrue,JsonString "abc",JsonArray []]
--
-- >>> parse jsonArray "[true, \"abc\", [false]]"
-- Result >< [JsonTrue,JsonString "abc",JsonArray [JsonFalse]]
jsonArray :: Parser (List JsonValue)
jsonArray = MP.betweenSepbyComma '[' ']' jsonValue
-- | Parse a JSON object.
--
-- /Tip:/ Use `jsonString`, `charTok`, `betweenSepbyComma` and `jsonValue`.
--
-- >>> parse jsonObject "{}"
-- Result >< []
--
-- >>> parse jsonObject "{ \"key1\" : true }"
-- Result >< [("key1",JsonTrue)]
--
-- >>> parse jsonObject "{ \"key1\" : true , \"key2\" : false }"
-- Result >< [("key1",JsonTrue),("key2",JsonFalse)]
--
-- >>> parse jsonObject "{ \"key1\" : true , \"key2\" : false } xyz"
-- Result >xyz< [("key1",JsonTrue),("key2",JsonFalse)]
jsonObject :: Parser Assoc
jsonObject = MP.betweenSepbyComma '{' '}' assoc
where
colon = MP.spaces A.*> MP.charTok ':'
assoc = A.lift3 (\k _ v -> (k, v)) jsonString colon jsonValue
simpleValue :: Parser JsonValue
simpleValue =
(JsonString F.<$> jsonString)
P.||| (JsonRational F.<$> jsonNumber)
P.||| (jsonTrue A.*> A.pure JsonTrue)
P.||| (jsonFalse A.*> A.pure JsonFalse)
P.||| (jsonNull A.*> A.pure JsonNull)
-- | Parse a JSON value.
--
-- /Tip:/ Use `spaces`, `jsonNull`, `jsonTrue`, `jsonFalse`, `jsonArray`, `jsonString`, `jsonObject` and `jsonNumber`.
--
-- >>> parse jsonValue "true"
-- Result >< JsonTrue
--
-- >>> parse jsonObject "{ \"key1\" : true , \"key2\" : [7, false] }"
-- Result >< [("key1",JsonTrue),("key2",JsonArray [JsonRational (7 % 1),JsonFalse])]
--
-- >>> parse jsonObject "{ \"key1\" : true , \"key2\" : [7, false] , \"key3\" : { \"key4\" : null } }"
-- Result >< [("key1",JsonTrue),("key2",JsonArray [JsonRational (7 % 1),JsonFalse]),("key3",JsonObject [("key4",JsonNull)])]
jsonValue :: Parser JsonValue
jsonValue =
MP.spaces
A.*> ( simpleValue
P.||| (JsonArray F.<$> jsonArray)
P.||| (JsonObject F.<$> jsonObject)
)
A.<* MP.spaces
-- | Read a file into a JSON value.
--
-- /Tip:/ Use @readFile@ and `jsonValue`.
readJsonValue :: FilePath -> IO (ParseResult JsonValue)
readJsonValue = (P.parse jsonValue F.<$>) . L.readFile