readme: add information section
[nit.git] / lib / json / static.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 # Copyright 2014 Alexandre Terrasa <alexandre@moz-concept.com>
5 # Copyright 2014 Jean-Christophe Beaupré <jcbrinfo@users.noreply.github.com>
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18
19 # Static interface to get Nit objects from a Json string.
20 #
21 # `Text::parse_json` returns an equivalent Nit object from
22 # the Json source. This object can then be type checked by the usual
23 # languages features (`isa` and `as`).
24 module static
25
26 import error
27 private import json_parser
28 private import json_lexer
29
30 # Something that can be translated to JSON.
31 interface Jsonable
32 # Encode `self` in JSON.
33 #
34 # SEE: `append_json`
35 fun to_json: String is abstract
36
37 # Use `append_json` to implement `to_json`.
38 #
39 # Therefore, one that redefine `append_json` may use the following
40 # redefinition to link `to_json` and `append_json`:
41 #
42 # ~~~nitish
43 # redef fun to_json do return to_json_by_append
44 # ~~~
45 #
46 # Note: This is not the default implementation of `to_json` in order to
47 # avoid cyclic references between `append_json` and `to_json` when none are
48 # implemented.
49 protected fun to_json_by_append: String do
50 var buffer = new FlatBuffer
51 append_json(buffer)
52 return buffer.to_s
53 end
54
55 # Append the JSON representation of `self` to the specified buffer.
56 #
57 # SEE: `to_json`
58 fun append_json(buffer: Buffer) do buffer.append(to_json)
59
60 # Pretty print JSON string.
61 #
62 # ~~~
63 # var obj = new JsonObject
64 # obj["foo"] = 1
65 # obj["bar"] = true
66 # var arr = new JsonArray
67 # arr.add 2
68 # arr.add false
69 # arr.add "baz"
70 # obj["baz"] = arr
71 # var res = obj.to_pretty_json
72 # var exp = """{
73 # \t"foo": 1,
74 # \t"bar": true,
75 # \t"baz": [2, false, "baz"]
76 # }\n"""
77 # assert res == exp
78 # ~~~
79 fun to_pretty_json: String do
80 var res = new FlatBuffer
81 pretty_json_visit(res, 0)
82 res.add '\n'
83 return res.to_s
84 end
85
86 private fun pretty_json_visit(buffer: FlatBuffer, indent: Int) is abstract
87 end
88
89 redef class Text
90 super Jsonable
91
92 # Removes JSON-escaping if necessary in a JSON string
93 #
94 # assert "\\\"string\\uD83D\\uDE02\\\"".unescape_json == "\"string😂\""
95 fun unescape_json: Text do
96 if not json_need_escape then return self
97 return self.json_to_nit_string
98 end
99
100 # Does `self` need treatment from JSON to Nit ?
101 #
102 # i.e. is there at least one `\` character in it ?
103 #
104 # assert not "string".json_need_escape
105 # assert "\\\"string\\\"".json_need_escape
106 protected fun json_need_escape: Bool do return has('\\')
107
108 redef fun append_json(buffer) do
109 buffer.add '\"'
110 for i in [0 .. self.length[ do
111 var char = self[i]
112 if char == '\\' then
113 buffer.append "\\\\"
114 else if char == '\"' then
115 buffer.append "\\\""
116 else if char < ' ' then
117 if char == '\n' then
118 buffer.append "\\n"
119 else if char == '\r' then
120 buffer.append "\\r"
121 else if char == '\t' then
122 buffer.append "\\t"
123 else
124 buffer.append char.escape_to_utf16
125 end
126 else
127 buffer.add char
128 end
129 end
130 buffer.add '\"'
131 end
132
133 # Escapes `self` from a JSON string to a Nit string
134 #
135 # assert "\\\"string\\\"".json_to_nit_string == "\"string\""
136 # assert "\\nEscape\\t\\n".json_to_nit_string == "\nEscape\t\n"
137 # assert "\\u0041zu\\uD800\\uDFD3".json_to_nit_string == "Azu𐏓"
138 protected fun json_to_nit_string: String do
139 var res = new FlatBuffer.with_capacity(bytelen)
140 var i = 0
141 while i < self.length do
142 var char = self[i]
143 if char == '\\' then
144 i += 1
145 char = self[i]
146 if char == 'b' then
147 char = 0x08.code_point
148 else if char == 'f' then
149 char = 0x0C.code_point
150 else if char == 'n' then
151 char = '\n'
152 else if char == 'r' then
153 char = '\r'
154 else if char == 't' then
155 char = '\t'
156 else if char == 'u' then
157 var code = substring(i + 1, 4)
158 var hx = code.to_hex
159 if hx >= 0xD800 and hx <= 0xDFFF then
160 var lostr = substring(i + 7, 4)
161 if lostr.length < 4 then
162 hx = 0xFFFD
163 else
164 hx <<= 16
165 hx += lostr.to_hex
166 hx = hx.from_utf16_surr
167 end
168 i += 6
169 end
170 i += 4
171 char = hx.code_point
172 end
173 # `"`, `/` or `\` => Keep `char` as-is.
174 end
175 res.add char
176 i += 1
177 end
178 return res.to_s
179 end
180
181
182 # Encode `self` in JSON.
183 #
184 # ~~~
185 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
186 # "\"\\t\\\"http://example.com\\\"\\r\\n\\u0000\\\\\""
187 # ~~~
188 redef fun to_json do
189 var b = new FlatBuffer.with_capacity(bytelen)
190 append_json(b)
191 return b.to_s
192 end
193
194 # Parse `self` as JSON.
195 #
196 # If `self` is not a valid JSON document or contains an unsupported escape
197 # sequence, return a `JSONParseError`.
198 #
199 # Example with `JsonObject`:
200 #
201 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
202 # assert obj isa JsonObject
203 # assert obj["foo"] isa JsonObject
204 # assert obj["foo"].as(JsonObject)["bar"] == true
205 #
206 # Example with `JsonArray`:
207 #
208 # var arr = "[1, 2, 3]".parse_json
209 # assert arr isa JsonArray
210 # assert arr.length == 3
211 # assert arr.first == 1
212 # assert arr.last == 3
213 #
214 # Example with `String`:
215 #
216 # var str = "\"foo, bar, baz\"".parse_json
217 # assert str isa String
218 # assert str == "foo, bar, baz"
219 #
220 # Example of a syntaxic error:
221 #
222 # var bad = "\{foo: \"bar\"\}".parse_json
223 # assert bad isa JsonParseError
224 # assert bad.position.col_start == 2
225 fun parse_json: nullable Jsonable do
226 var lexer = new Lexer_json(to_s)
227 var parser = new Parser_json
228 var tokens = lexer.lex
229 parser.tokens.add_all(tokens)
230 var root_node = parser.parse
231 if root_node isa NStart then
232 return root_node.n_0.to_nit_object
233 else if root_node isa NError then
234 return new JsonParseError(root_node.message, root_node.position)
235 else abort
236 end
237 end
238
239 redef class FlatText
240 redef fun json_need_escape do
241 var its = items
242 for i in [first_byte .. last_byte] do
243 if its[i] == 0x5Cu8 then return true
244 end
245 return false
246 end
247 end
248
249 redef class Buffer
250
251 # Append the JSON representation of `jsonable` to `self`.
252 #
253 # Append `"null"` for `null`.
254 private fun append_json_of(jsonable: nullable Jsonable) do
255 if jsonable isa Jsonable then
256 append jsonable.to_json
257 else
258 append "null"
259 end
260 end
261 end
262
263 redef class Int
264 super Jsonable
265
266 # Encode `self` in JSON.
267 #
268 # assert 0.to_json == "0"
269 # assert (-42).to_json == "-42"
270 redef fun to_json do return self.to_s
271 end
272
273 redef class Float
274 super Jsonable
275
276 # Encode `self` in JSON.
277 #
278 # Note: Because this method use `to_s`, it may lose precision.
279 #
280 # ~~~
281 # # Will not work as expected.
282 # # assert (-0.0).to_json == "-0.0"
283 #
284 # assert (.5).to_json == "0.5"
285 # assert (0.0).to_json == "0.0"
286 # ~~~
287 redef fun to_json do return self.to_s
288 end
289
290 redef class Bool
291 super Jsonable
292
293 # Encode `self` in JSON.
294 #
295 # assert true.to_json == "true"
296 # assert false.to_json == "false"
297 redef fun to_json do return self.to_s
298 end
299
300 # A map that can be translated into a JSON object.
301 interface JsonMapRead[K: String, V: nullable Jsonable]
302 super MapRead[K, V]
303 super Jsonable
304
305 redef fun append_json(buffer) do
306 buffer.append "\{"
307 var it = iterator
308 if it.is_ok then
309 append_json_entry(it, buffer)
310 while it.is_ok do
311 buffer.append ","
312 append_json_entry(it, buffer)
313 end
314 end
315 it.finish
316 buffer.append "\}"
317 end
318
319 # Encode `self` in JSON.
320 #
321 # var obj = new JsonObject
322 # obj["foo"] = "bar"
323 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
324 # obj = new JsonObject
325 # obj["baz"] = null
326 # assert obj.to_json == "\{\"baz\":null\}"
327 redef fun to_json do return to_json_by_append
328
329 redef fun pretty_json_visit(buffer, indent) do
330 buffer.append "\{\n"
331 indent += 1
332 var i = 0
333 for k, v in self do
334 buffer.append "\t" * indent
335 buffer.append "\"{k}\": "
336 if v isa JsonObject or v isa JsonArray then
337 v.pretty_json_visit(buffer, indent)
338 else
339 buffer.append v.to_json
340 end
341 if i < length - 1 then
342 buffer.append ","
343 end
344 buffer.append "\n"
345 i += 1
346 end
347 indent -= 1
348 buffer.append "\t" * indent
349 buffer.append "\}"
350 end
351
352 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
353 buffer: Buffer) do
354 buffer.append iterator.key.to_json
355 buffer.append ":"
356 buffer.append_json_of(iterator.item)
357 iterator.next
358 end
359 end
360
361 # A JSON Object.
362 class JsonObject
363 super JsonMapRead[String, nullable Jsonable]
364 super HashMap[String, nullable Jsonable]
365 end
366
367 # A sequence that can be translated into a JSON array.
368 class JsonSequenceRead[E: nullable Jsonable]
369 super Jsonable
370 super SequenceRead[E]
371
372 redef fun append_json(buffer) do
373 buffer.append "["
374 var it = iterator
375 if it.is_ok then
376 append_json_entry(it, buffer)
377 while it.is_ok do
378 buffer.append ","
379 append_json_entry(it, buffer)
380 end
381 end
382 it.finish
383 buffer.append "]"
384 end
385
386 # Encode `self` in JSON.
387 #
388 # var arr = new JsonArray.with_items("foo", null)
389 # assert arr.to_json == "[\"foo\",null]"
390 # arr.pop
391 # assert arr.to_json =="[\"foo\"]"
392 # arr.pop
393 # assert arr.to_json =="[]"
394 redef fun to_json do return to_json_by_append
395
396 redef fun pretty_json_visit(buffer, indent) do
397 buffer.append "\["
398 var i = 0
399 for v in self do
400 if v isa JsonObject or v isa JsonArray then
401 v.pretty_json_visit(buffer, indent)
402 else
403 buffer.append v.to_json
404 end
405 if i < length - 1 then buffer.append ", "
406 i += 1
407 end
408 buffer.append "\]"
409 end
410
411 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
412 buffer: Buffer) do
413 buffer.append_json_of(iterator.item)
414 iterator.next
415 end
416 end
417
418 # A JSON array.
419 class JsonArray
420 super JsonSequenceRead[nullable Jsonable]
421 super Array[nullable Jsonable]
422 end
423
424 redef class JsonParseError
425 super Jsonable
426
427 # Get the JSON representation of `self`.
428 #
429 # ~~~
430 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
431 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
432 # "\"position\":\{" +
433 # "\"pos_start\":1,\"pos_end\":2," +
434 # "\"line_start\":3,\"line_end\":4," +
435 # "\"col_start\":5,\"col_end\":6" +
436 # "\},\"message\":\"foo\"\}"
437 # ~~~
438 redef fun to_json do
439 return "\{\"error\":\"JsonParseError\"," +
440 "\"position\":{position.to_json}," +
441 "\"message\":{message.to_json}\}"
442 end
443 end
444
445 redef class Position
446 super Jsonable
447
448 # Get the JSON representation of `self`.
449 #
450 # ~~~
451 # var pos = new Position(1, 2, 3, 4, 5, 6)
452 # assert pos.to_json == "\{" +
453 # "\"pos_start\":1,\"pos_end\":2," +
454 # "\"line_start\":3,\"line_end\":4," +
455 # "\"col_start\":5,\"col_end\":6" +
456 # "\}"
457 # ~~~
458 redef fun to_json do
459 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
460 "\"line_start\":{line_start},\"line_end\":{line_end}," +
461 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
462 end
463 end
464
465 ################################################################################
466 # Redef parser
467
468 redef class Nvalue
469 # The represented value.
470 private fun to_nit_object: nullable Jsonable is abstract
471 end
472
473 redef class Nvalue_number
474 redef fun to_nit_object
475 do
476 var text = n_number.text
477 if text.chars.has('.') or text.chars.has('e') or text.chars.has('E') then return text.to_f
478 return text.to_i
479 end
480 end
481
482 redef class Nvalue_string
483 redef fun to_nit_object do return n_string.to_nit_string
484 end
485
486 redef class Nvalue_true
487 redef fun to_nit_object do return true
488 end
489
490 redef class Nvalue_false
491 redef fun to_nit_object do return false
492 end
493
494 redef class Nvalue_null
495 redef fun to_nit_object do return null
496 end
497
498 redef class Nstring
499 # The represented string.
500 private fun to_nit_string: String do return text.substring(1, text.length - 2).unescape_json.to_s
501 end
502
503 redef class Nvalue_object
504 redef fun to_nit_object do
505 var obj = new JsonObject
506 var members = n_members
507 if members != null then
508 var pairs = members.pairs
509 for pair in pairs do obj[pair.name] = pair.value
510 end
511 return obj
512 end
513 end
514
515 redef class Nmembers
516 # All the key-value pairs.
517 private fun pairs: Array[Npair] is abstract
518 end
519
520 redef class Nmembers_tail
521 redef fun pairs
522 do
523 var arr = n_members.pairs
524 arr.add n_pair
525 return arr
526 end
527 end
528
529 redef class Nmembers_head
530 redef fun pairs do return [n_pair]
531 end
532
533 redef class Npair
534 # The represented key.
535 private fun name: String do return n_string.to_nit_string
536
537 # The represented value.
538 private fun value: nullable Jsonable do return n_value.to_nit_object
539 end
540
541 redef class Nvalue_array
542 redef fun to_nit_object
543 do
544 var arr = new JsonArray
545 var elements = n_elements
546 if elements != null then
547 var items = elements.items
548 for item in items do arr.add(item.to_nit_object)
549 end
550 return arr
551 end
552 end
553
554 redef class Nelements
555 # All the items.
556 private fun items: Array[Nvalue] is abstract
557 end
558
559 redef class Nelements_tail
560 redef fun items
561 do
562 var items = n_elements.items
563 items.add(n_value)
564 return items
565 end
566 end
567
568 redef class Nelements_head
569 redef fun items do return [n_value]
570 end