1 # This file is part of NIT ( http://www.nitlanguage.org ).
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>
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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.
19 # Static interface to get Nit objects from a Json string.
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`).
27 private import json_parser
28 private import json_lexer
30 # Something that can be translated to JSON.
32 # Encode `self` in JSON.
34 # This is a recursive method which can be refined by any subclasses.
35 # To write any `Serializable` object to JSON, see `serialize_to_json`.
38 fun to_json
: String is abstract
40 # Use `append_json` to implement `to_json`.
42 # Therefore, one that redefine `append_json` may use the following
43 # redefinition to link `to_json` and `append_json`:
46 # redef fun to_json do return to_json_by_append
49 # Note: This is not the default implementation of `to_json` in order to
50 # avoid cyclic references between `append_json` and `to_json` when none are
52 protected fun to_json_by_append
: String do
53 var buffer
= new FlatBuffer
58 # Append the JSON representation of `self` to the specified buffer.
61 fun append_json
(buffer
: Buffer) do buffer
.append
(to_json
)
63 # Pretty print JSON string.
66 # var obj = new JsonObject
69 # var arr = new JsonArray
74 # var res = obj.to_pretty_json
78 # \t"baz": [2, false, "baz"]
82 fun to_pretty_json
: String do
83 var res
= new FlatBuffer
84 pretty_json_visit
(res
, 0)
89 private fun pretty_json_visit
(buffer
: FlatBuffer, indent
: Int) is abstract
95 # Removes JSON-escaping if necessary in a JSON string
97 # assert "\\\"string\\uD83D\\uDE02\\\"".unescape_json == "\"string😂\""
98 fun unescape_json
: Text do
99 if not json_need_escape
then return self
100 return self.json_to_nit_string
103 # Does `self` need treatment from JSON to Nit ?
105 # i.e. is there at least one `\` character in it ?
107 # assert not "string".json_need_escape
108 # assert "\\\"string\\\"".json_need_escape
109 protected fun json_need_escape
: Bool do return has
('\\')
111 redef fun append_json
(buffer
) do
113 for i
in [0 .. self.length
[ do
117 else if char
== '\"' then
119 else if char < ' ' then
122 else if char == '\r' then
124 else if char == '\t' then
127 buffer.append char.escape_to_utf16
136 # Escapes `self` from a JSON string to a Nit string
138 # assert "\\\"string\\\"".json_to_nit_string == "\"string\""
139 # assert "\\nEscape\\t\\n".json_to_nit_string == "\nEscape\t\n"
140 # assert "\\u0041zu\\uD800\\uDFD3".json_to_nit_string == "Azu𐏓"
141 protected fun json_to_nit_string: String do
142 var res = new FlatBuffer.with_capacity(bytelen)
151 char = 0x08.code_point
152 else if char == 'f
' then
153 char = 0x0C.code_point
154 else if char == 'n
' then
156 else if char == 'r
' then
158 else if char == 't
' then
160 else if char == 'u
' then
161 var u16_esc = from_utf16_digit(i + 1)
162 char = u16_esc.code_point
163 if char.is_surrogate and i + 10 < ln then
164 if self[i + 5] == '\\
' and self[i + 6] == 'u
' then
166 u16_esc += from_utf16_digit(i + 7)
167 char = u16_esc.from_utf16_surr.code_point
170 char = 0xFFFD.code_point
175 # `"`, `/` or `\` => Keep `char` as-is.
184 # Encode `self` in JSON.
187 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
188 # "\"\\t\\\"http://example.com\\\"\\r\\n\\u0000\\\\\""
191 var b = new FlatBuffer.with_capacity(bytelen)
196 # Parse `self` as JSON.
198 # If `self` is not a valid JSON document or contains an unsupported escape
199 # sequence, return a `JSONParseError`.
201 # Example with `JsonObject`:
203 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
204 # assert obj isa JsonObject
205 # assert obj["foo"] isa JsonObject
206 # assert obj["foo"].as(JsonObject)["bar"] == true
208 # Example with `JsonArray`:
210 # var arr = "[1, 2, 3]".parse_json
211 # assert arr isa JsonArray
212 # assert arr.length == 3
213 # assert arr.first == 1
214 # assert arr.last == 3
216 # Example with `String`:
218 # var str = "\"foo, bar, baz\"".parse_json
219 # assert str isa String
220 # assert str == "foo, bar, baz"
222 # Example of a syntaxic error:
224 # var bad = "\{foo: \"bar\"\}".parse_json
225 # assert bad isa JsonParseError
226 # assert bad.position.col_start == 2
227 fun parse_json: nullable Jsonable do
228 var lexer = new Lexer_json(to_s)
229 var parser = new Parser_json
230 var tokens = lexer.lex
231 parser.tokens.add_all(tokens)
232 var root_node = parser.parse
233 if root_node isa NStart then
234 return root_node.n_0.to_nit_object
235 else if root_node isa NError then
236 return new JsonParseError(root_node.message, root_node.position)
242 redef fun json_need_escape do
244 for i in [first_byte .. last_byte] do
245 if its[i] == 0x5Cu8 then return true
253 # Append the JSON representation of `jsonable` to `self`.
255 # Append `"null"` for `null`.
256 private fun append_json_of(jsonable: nullable Jsonable) do
257 if jsonable isa Jsonable then
258 append jsonable.to_json
268 # Encode `self` in JSON.
270 # assert 0.to_json == "0"
271 # assert (-42).to_json == "-42"
272 redef fun to_json do return self.to_s
278 # Encode `self` in JSON.
280 # Note: Because this method use `to_s`, it may lose precision.
283 # # Will not work as expected.
284 # # assert (-0.0).to_json == "-0.0"
286 # assert (.5).to_json == "0.5"
287 # assert (0.0).to_json == "0.0"
289 redef fun to_json do return self.to_s
295 # Encode `self` in JSON.
297 # assert true.to_json == "true"
298 # assert false.to_json == "false"
299 redef fun to_json do return self.to_s
302 # A map that can be translated into a JSON object.
303 interface JsonMapRead[K: String, V: nullable Jsonable]
307 redef fun append_json(buffer) do
311 append_json_entry(it, buffer)
314 append_json_entry(it, buffer)
321 # Encode `self` in JSON.
323 # var obj = new JsonObject
325 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
326 # obj = new JsonObject
328 # assert obj.to_json == "\{\"baz\":null\}"
329 redef fun to_json do return to_json_by_append
331 redef fun pretty_json_visit(buffer, indent) do
336 buffer.append "\t" * indent
337 buffer.append "\"{k}\": "
338 if v isa JsonObject or v isa JsonArray then
339 v.pretty_json_visit(buffer, indent)
341 buffer.append v.to_json
343 if i < length - 1 then
350 buffer.append "\t" * indent
354 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
356 buffer.append iterator.key.to_json
358 buffer.append_json_of(iterator.item)
365 super JsonMapRead[String, nullable Jsonable]
366 super HashMap[String, nullable Jsonable]
369 # A sequence that can be translated into a JSON array.
370 class JsonSequenceRead[E: nullable Jsonable]
372 super SequenceRead[E]
374 redef fun append_json(buffer) do
378 append_json_entry(it, buffer)
381 append_json_entry(it, buffer)
388 # Encode `self` in JSON.
390 # var arr = new JsonArray.with_items("foo", null)
391 # assert arr.to_json == "[\"foo\",null]"
393 # assert arr.to_json =="[\"foo\"]"
395 # assert arr.to_json =="[]"
396 redef fun to_json do return to_json_by_append
398 redef fun pretty_json_visit(buffer, indent) do
402 if v isa JsonObject or v isa JsonArray then
403 v.pretty_json_visit(buffer, indent)
405 buffer.append v.to_json
407 if i < length - 1 then buffer.append ", "
413 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
415 buffer.append_json_of(iterator.item)
422 super JsonSequenceRead[nullable Jsonable]
423 super Array[nullable Jsonable]
426 redef class JsonParseError
429 # Get the JSON representation of `self`.
432 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
433 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
434 # "\"position\":\{" +
435 # "\"pos_start\":1,\"pos_end\":2," +
436 # "\"line_start\":3,\"line_end\":4," +
437 # "\"col_start\":5,\"col_end\":6" +
438 # "\},\"message\":\"foo\"\}"
441 return "\{\"error\":\"JsonParseError\"," +
442 "\"position\":{position.to_json}," +
443 "\"message\":{message.to_json}\}"
446 redef fun pretty_json_visit(buf, indents) do
455 # Get the JSON representation of `self`.
458 # var pos = new Position(1, 2, 3, 4, 5, 6)
459 # assert pos.to_json == "\{" +
460 # "\"pos_start\":1,\"pos_end\":2," +
461 # "\"line_start\":3,\"line_end\":4," +
462 # "\"col_start\":5,\"col_end\":6" +
466 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
467 "\"line_start\":{line_start},\"line_end\":{line_end}," +
468 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
472 ################################################################################
476 # The represented value.
477 private fun to_nit_object: nullable Jsonable is abstract
480 redef class Nvalue_number
481 redef fun to_nit_object
483 var text = n_number.text
484 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
489 redef class Nvalue_string
490 redef fun to_nit_object do return n_string.to_nit_string
493 redef class Nvalue_true
494 redef fun to_nit_object do return true
497 redef class Nvalue_false
498 redef fun to_nit_object do return false
501 redef class Nvalue_null
502 redef fun to_nit_object do return null
506 # The represented string.
507 private fun to_nit_string: String do return text.substring(1, text.length - 2).unescape_json.to_s
510 redef class Nvalue_object
511 redef fun to_nit_object do
512 var obj = new JsonObject
513 var members = n_members
514 if members != null then
515 var pairs = members.pairs
516 for pair in pairs do obj[pair.name] = pair.value
523 # All the key-value pairs.
524 private fun pairs: Array[Npair] is abstract
527 redef class Nmembers_tail
530 var arr = n_members.pairs
536 redef class Nmembers_head
537 redef fun pairs do return [n_pair]
541 # The represented key.
542 private fun name: String do return n_string.to_nit_string
544 # The represented value.
545 private fun value: nullable Jsonable do return n_value.to_nit_object
548 redef class Nvalue_array
549 redef fun to_nit_object
551 var arr = new JsonArray
552 var elements = n_elements
553 if elements != null then
554 var items = elements.items
555 for item in items do arr.add(item.to_nit_object)
561 redef class Nelements
563 private fun items: Array[Nvalue] is abstract
566 redef class Nelements_tail
569 var items = n_elements.items
575 redef class Nelements_head
576 redef fun items do return [n_value]