-
Notifications
You must be signed in to change notification settings - Fork 2
/
json_parser.rb
324 lines (261 loc) · 10.3 KB
/
json_parser.rb
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
# Exercise from Ruby Quiz: http://rubyquiz.com/quiz155.html
# Borrowed heavily from TreeTop parser used in http://learnruby.com/examples/ruby-quiz-155.shtml
require "bundler/setup"
require "minitest/autorun"
require "speculation"
require "speculation/gen"
require "speculation/test"
S = Speculation
Gen = S::Gen
STest = S::Test
module JSONParser
extend S::NamespacedSymbols
def self.re_literal(string)
kvs = string.each_char.each_with_index.reduce({}) { |h, (v, i)| h.merge(i => Set[v]) }
S.cat(kvs)
end
S.def ns(:maybe_spaces), S.zero_or_more(Set[" "])
S.def ns(:boolean), S.alt(:true => re_literal("true"),
:false => re_literal("false"))
S.def ns(:number), S.alt(:integer => ns(:integer),
:float => ns(:float))
S.def ns(:digit), S.with_gen(/\A[[:digit:]]\z/) { Radagen.char_numeric }
S.def ns(:digits), S.one_or_more(ns(:digit))
S.def ns(:exp), Set["e", "E"]
S.def ns(:maybe_sign), S.zero_or_one(Set["-", "+"])
S.def ns(:exponent), S.cat(:pre => ns(:exp),
:sign => ns(:maybe_sign),
:digits => ns(:digits))
S.def ns(:maybe_exponent), S.zero_or_one(ns(:exponent))
S.def ns(:integer), S.cat(:neg => S.zero_or_one(Set["-"]),
:digits => ns(:digits),
:exponent => ns(:maybe_exponent))
S.def ns(:maybe_neg), S.zero_or_one(Set["-"])
S.def ns(:float), S.cat(:neg => ns(:maybe_neg),
:digits => ns(:digits),
:dot => Set["."],
:more_digits => ns(:digits),
:exponent => ns(:maybe_exponent))
S.def ns(:quote), Set['"']
S.def ns(:maybe_characters), S.zero_or_more(ns(:character))
S.def ns(:string), S.cat(:open => ns(:quote),
:contents => ns(:maybe_characters),
:close => ns(:quote))
S.def ns(:character), S.alt(:escaped => ns(:escaped_character),
:special => ns(:special_character),
:unicode => ns(:unicode_character),
:regular => ns(:regular_character))
S.def ns(:unicode_character), S.with_gen(S.cat(:escape => Set['\\'],
:u => Set['u'],
:digits => S.constrained(S.one_or_more(ns(:hex_digit)), ->(digits) { digits.count == 4 }))) { Radagen.identity("\\u00b5".chars) }
S.def ns(:hex_digit), /[0-9a-fA-F]/
S.def ns(:escaped_character), S.cat(:escape => Set['\\'],
:val => Set['\\', '"'])
special_character_map = {
"b" => "\b",
"f" => "\f",
"n" => "\n",
"r" => "\r",
"t" => "\t",
}
S.def ns(:special_character), S.cat(:escape => Set['\\'],
:val => Set['b', 'f', 'n', 'r', 't'])
S.def ns(:regular_character), S.with_gen(->(s) { !['\\', '"'].include?(s) }) { Radagen.char_ascii }
S.def ns(:open_square_bracket), Set["["]
S.def ns(:close_square_bracket), Set["]"]
S.def ns(:empty_array), S.cat(:open => ns(:open_square_bracket),
:spaces => ns(:maybe_spaces),
:close => ns(:close_square_bracket))
S.def ns(:non_empty_array), S.cat(:open => ns(:open_square_bracket),
:space => ns(:maybe_spaces),
:value_list => ns(:value_list),
:more_space => ns(:maybe_spaces),
:close => ns(:close_square_bracket))
S.def ns(:array), S.alt(:non_empty => ns(:non_empty_array),
:empty => ns(:empty_array))
S.def ns(:value_list), S.alt(:val => ns(:json),
:rest => S.cat(:val => ns(:json),
:comma => Set[","],
:space => ns(:maybe_spaces),
:tail => ns(:value_list)))
S.def ns(:open_brace), Set["{"]
S.def ns(:close_brace), Set["}"]
S.def ns(:empty_object), S.cat(:open => ns(:open_brace),
:spaces => ns(:maybe_spaces),
:close => ns(:close_brace))
S.def ns(:non_empty_object), S.cat(:open => ns(:open_brace),
:spaces => ns(:maybe_spaces),
:contents => ns(:object_contents),
:more_spaces => ns(:maybe_spaces),
:close => ns(:close_brace))
S.def ns(:object), S.alt(:empty_object => ns(:empty_object),
:non_empty_object => ns(:non_empty_object))
S.def ns(:kv), S.cat(:before => ns(:maybe_spaces),
:key => ns(:string),
:colon => Set[":"],
:after => ns(:maybe_spaces),
:val => ns(:json))
S.def ns(:object_contents), S.alt(:kv => ns(:kv),
:rest => S.cat(:kv => ns(:kv),
:comma => Set[","],
:space => ns(:maybe_spaces),
:tail => ns(:object_contents)))
S.def ns(:json), S.cat(:pre => ns(:maybe_spaces),
:val => S.alt(:null => re_literal("null"),
:boolean => ns(:boolean),
:number => ns(:number),
:string => ns(:string),
:array => ns(:array),
:object => ns(:object)),
:post => ns(:maybe_spaces))
def self.parse(s)
chars = s.split("")
json_data = S.conform(ns(:json), chars)
if S.invalid?(json_data)
fail S.explain_str(ns(:json), chars)
else
transform_json(json_data)
end
end
def self.transform_json(data)
tag, val = data[:val]
case tag
when :boolean then transform_boolean(val)
when :null then nil
when :number then transform_number(val)
when :string then transform_string(val)
when :array then transform_array(val)
when :object then transform_object(val)
end
end
def self.transform_boolean(tagged_val)
tag, val = tagged_val
case tag
when :true then true
when :false then false
end
end
def self.transform_number(tagged_val)
tag, val = tagged_val
case tag
when :integer
Integer(val.values_at(:neg, :digits, :exponent).join)
when :float
exp = Hash(val[:exponent]).values_at(:pre, :sign, :digits).join
val = val.merge(:exp => exp)
Float(val.values_at(:neg, :digits, :dot, :more_digits, :exp).join)
end
end
SPECIAL_CHARACTER_MAP = {
"b" => "\b",
"f" => "\f",
"n" => "\n",
"r" => "\r",
"t" => "\t",
}
def self.transform_string(val)
Array(val[:contents]).map { |(tag, char)|
case tag
when :regular then char
when :special then SPECIAL_CHARACTER_MAP.fetch(char[:val])
when :escaped then char[:val]
when :unicode then [char[:digits].join.hex].pack("U")
end
}.join
end
def self.transform_array(tagged_val)
tag, val = tagged_val
case tag
when :empty then []
when :non_empty then transform_value_list(val[:value_list])
end
end
def self.transform_value_list(tagged_val)
tag, val = tagged_val
case tag
when :rest
head = [transform_json(val[:val])]
tail = transform_value_list(val[:tail])
head + tail
when :val
[transform_json(val)]
end
end
def self.transform_object(tagged_val)
tag, val = tagged_val
case tag
when :empty_object then {}
when :non_empty_object then transform_object_contents(val[:contents])
end
end
def self.transform_object_contents(tagged_val)
tag, val = tagged_val
case tag
when :kv
{ transform_string(val[:key]) => transform_json(val[:val]) }
when :rest
transform_object_contents([:kv, val[:kv]]).
merge(transform_object_contents(val[:tail]))
end
end
end
class TestJSONParser < Minitest::Test
def test_keyword_parsing
assert_parses true, "true"
assert_parses false, "false"
assert_parses nil, "null"
end
def test_number_parsing
assert_parses 42, "42"
assert_parses -13, "-13"
assert_parses 3.1415, "3.1415"
assert_parses -0.01, "-0.01"
assert_parses 0.2e1, "0.2e1"
assert_parses 0.2e+1, "0.2e+1"
assert_parses 0.2e-1, "0.2e-1"
assert_parses 0.2E1, "0.2e1"
end
def test_string_parsing
assert_parses String.new, '""'
assert_parses "JSON", '"JSON"'
assert_parses 'nested "quotes"', '"nested \"quotes\""'
assert_parses "\n", '"\\n"'
assert_parses "µ", '"\\u00b5"'
end
def test_array_parsing
assert_parses [], '[]'
assert_parses ["foo", "bar", "baz"], '["foo", "bar", "baz"]'
assert_parses ["JSON", 3.1415, true], '["JSON", 3.1415, true]'
assert_parses [1, [2, [3]]], '[1, [2, [3]]]'
end
def test_object_parsing
assert_parses Hash[], '{}'
assert_parses Hash["foo" => "bar"], '{"foo": "bar"}'
assert_parses Hash["foo" => "bar", "baz" => "qux"], '{"foo": "bar", "baz": "qux"}'
assert_parses Hash["JSON" => 3.1415, "data" => true], '{"JSON": 3.1415, "data": true}'
assert_parses Hash["Array" => [1, 2, 3], "Object" => {"nested" => "objects"}],
'{"Array": [1, 2, 3], "Object": {"nested": "objects"}}'
end
def test_parse_errors
assert_invalid "{"
assert_invalid %q{{"key": true false}}
assert_invalid "["
assert_invalid "[1,,2]"
assert_invalid '"'
assert_invalid '"\\i"'
assert_invalid "$1,000"
assert_invalid "1_000"
assert_invalid "1K"
assert_invalid "unknown"
end
def assert_invalid(json_string)
assert_raises(RuntimeError) { JSONParser.parse(json_string) }
end
def assert_parses(expected_val, json_string)
if expected_val.nil?
assert_nil(JSONParser.parse(json_string))
else
assert_equal(expected_val, JSONParser.parse(json_string))
end
end
end