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.
35 fun to_json
: String is abstract
37 # Use `append_json` to implement `to_json`.
39 # Therefore, one that redefine `append_json` may use the following
40 # redefinition to link `to_json` and `append_json`:
43 # redef fun to_json do return to_json_by_append
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
49 protected fun to_json_by_append
: String do
50 var buffer
= new FlatBuffer
55 # Append the JSON representation of `self` to the specified buffer.
58 fun append_json
(buffer
: Buffer) do buffer
.append
(to_json
)
60 # Pretty print JSON string.
63 # var obj = new JsonObject
66 # var arr = new JsonArray
71 # var res = obj.to_pretty_json
75 # \t"baz": [2, false, "baz"]
79 fun to_pretty_json
: String do
80 var res
= new FlatBuffer
81 pretty_json_visit
(res
, 0)
86 private fun pretty_json_visit
(buffer
: FlatBuffer, indent
: Int) is abstract
92 # Removes JSON-escaping if necessary in a JSON string
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
100 # Does `self` need treatment from JSON to Nit ?
102 # i.e. is there at least one `\` character in it ?
104 # assert not "string".json_need_escape
105 # assert "\\\"string\\\"".json_need_escape
106 protected fun json_need_escape
: Bool do return has
('\\')
108 redef fun append_json
(buffer
) do
110 for i
in [0 .. self.length
[ do
114 else if char
== '\"' then
116 else if char < ' ' then
119 else if char == '\r' then
121 else if char == '\t' then
124 buffer.append char.escape_to_utf16
133 # Escapes `self` from a JSON string to a Nit string
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)
148 char = 0x08.code_point
149 else if char == 'f
' then
150 char = 0x0C.code_point
151 else if char == 'n
' then
153 else if char == 'r
' then
155 else if char == 't
' then
157 else if char == 'u
' then
158 var u16_esc = from_utf16_digit(i + 1)
159 char = u16_esc.code_point
160 if char.is_surrogate and i + 10 < ln then
161 if self[i + 5] == '\\
' and self[i + 6] == 'u
' then
163 u16_esc += from_utf16_digit(i + 7)
164 char = u16_esc.from_utf16_surr.code_point
167 char = 0xFFFD.code_point
172 # `"`, `/` or `\` => Keep `char` as-is.
181 # Encode `self` in JSON.
184 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
185 # "\"\\t\\\"http://example.com\\\"\\r\\n\\u0000\\\\\""
188 var b = new FlatBuffer.with_capacity(bytelen)
193 # Parse `self` as JSON.
195 # If `self` is not a valid JSON document or contains an unsupported escape
196 # sequence, return a `JSONParseError`.
198 # Example with `JsonObject`:
200 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
201 # assert obj isa JsonObject
202 # assert obj["foo"] isa JsonObject
203 # assert obj["foo"].as(JsonObject)["bar"] == true
205 # Example with `JsonArray`:
207 # var arr = "[1, 2, 3]".parse_json
208 # assert arr isa JsonArray
209 # assert arr.length == 3
210 # assert arr.first == 1
211 # assert arr.last == 3
213 # Example with `String`:
215 # var str = "\"foo, bar, baz\"".parse_json
216 # assert str isa String
217 # assert str == "foo, bar, baz"
219 # Example of a syntaxic error:
221 # var bad = "\{foo: \"bar\"\}".parse_json
222 # assert bad isa JsonParseError
223 # assert bad.position.col_start == 2
224 fun parse_json: nullable Jsonable do
225 var lexer = new Lexer_json(to_s)
226 var parser = new Parser_json
227 var tokens = lexer.lex
228 parser.tokens.add_all(tokens)
229 var root_node = parser.parse
230 if root_node isa NStart then
231 return root_node.n_0.to_nit_object
232 else if root_node isa NError then
233 return new JsonParseError(root_node.message, root_node.position)
239 redef fun json_need_escape do
241 for i in [first_byte .. last_byte] do
242 if its[i] == 0x5Cu8 then return true
250 # Append the JSON representation of `jsonable` to `self`.
252 # Append `"null"` for `null`.
253 private fun append_json_of(jsonable: nullable Jsonable) do
254 if jsonable isa Jsonable then
255 append jsonable.to_json
265 # Encode `self` in JSON.
267 # assert 0.to_json == "0"
268 # assert (-42).to_json == "-42"
269 redef fun to_json do return self.to_s
275 # Encode `self` in JSON.
277 # Note: Because this method use `to_s`, it may lose precision.
280 # # Will not work as expected.
281 # # assert (-0.0).to_json == "-0.0"
283 # assert (.5).to_json == "0.5"
284 # assert (0.0).to_json == "0.0"
286 redef fun to_json do return self.to_s
292 # Encode `self` in JSON.
294 # assert true.to_json == "true"
295 # assert false.to_json == "false"
296 redef fun to_json do return self.to_s
299 # A map that can be translated into a JSON object.
300 interface JsonMapRead[K: String, V: nullable Jsonable]
304 redef fun append_json(buffer) do
308 append_json_entry(it, buffer)
311 append_json_entry(it, buffer)
318 # Encode `self` in JSON.
320 # var obj = new JsonObject
322 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
323 # obj = new JsonObject
325 # assert obj.to_json == "\{\"baz\":null\}"
326 redef fun to_json do return to_json_by_append
328 redef fun pretty_json_visit(buffer, indent) do
333 buffer.append "\t" * indent
334 buffer.append "\"{k}\": "
335 if v isa JsonObject or v isa JsonArray then
336 v.pretty_json_visit(buffer, indent)
338 buffer.append v.to_json
340 if i < length - 1 then
347 buffer.append "\t" * indent
351 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
353 buffer.append iterator.key.to_json
355 buffer.append_json_of(iterator.item)
362 super JsonMapRead[String, nullable Jsonable]
363 super HashMap[String, nullable Jsonable]
366 # A sequence that can be translated into a JSON array.
367 class JsonSequenceRead[E: nullable Jsonable]
369 super SequenceRead[E]
371 redef fun append_json(buffer) do
375 append_json_entry(it, buffer)
378 append_json_entry(it, buffer)
385 # Encode `self` in JSON.
387 # var arr = new JsonArray.with_items("foo", null)
388 # assert arr.to_json == "[\"foo\",null]"
390 # assert arr.to_json =="[\"foo\"]"
392 # assert arr.to_json =="[]"
393 redef fun to_json do return to_json_by_append
395 redef fun pretty_json_visit(buffer, indent) do
399 if v isa JsonObject or v isa JsonArray then
400 v.pretty_json_visit(buffer, indent)
402 buffer.append v.to_json
404 if i < length - 1 then buffer.append ", "
410 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
412 buffer.append_json_of(iterator.item)
419 super JsonSequenceRead[nullable Jsonable]
420 super Array[nullable Jsonable]
423 redef class JsonParseError
426 # Get the JSON representation of `self`.
429 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
430 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
431 # "\"position\":\{" +
432 # "\"pos_start\":1,\"pos_end\":2," +
433 # "\"line_start\":3,\"line_end\":4," +
434 # "\"col_start\":5,\"col_end\":6" +
435 # "\},\"message\":\"foo\"\}"
438 return "\{\"error\":\"JsonParseError\"," +
439 "\"position\":{position.to_json}," +
440 "\"message\":{message.to_json}\}"
447 # Get the JSON representation of `self`.
450 # var pos = new Position(1, 2, 3, 4, 5, 6)
451 # assert pos.to_json == "\{" +
452 # "\"pos_start\":1,\"pos_end\":2," +
453 # "\"line_start\":3,\"line_end\":4," +
454 # "\"col_start\":5,\"col_end\":6" +
458 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
459 "\"line_start\":{line_start},\"line_end\":{line_end}," +
460 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
464 ################################################################################
468 # The represented value.
469 private fun to_nit_object: nullable Jsonable is abstract
472 redef class Nvalue_number
473 redef fun to_nit_object
475 var text = n_number.text
476 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
481 redef class Nvalue_string
482 redef fun to_nit_object do return n_string.to_nit_string
485 redef class Nvalue_true
486 redef fun to_nit_object do return true
489 redef class Nvalue_false
490 redef fun to_nit_object do return false
493 redef class Nvalue_null
494 redef fun to_nit_object do return null
498 # The represented string.
499 private fun to_nit_string: String do return text.substring(1, text.length - 2).unescape_json.to_s
502 redef class Nvalue_object
503 redef fun to_nit_object do
504 var obj = new JsonObject
505 var members = n_members
506 if members != null then
507 var pairs = members.pairs
508 for pair in pairs do obj[pair.name] = pair.value
515 # All the key-value pairs.
516 private fun pairs: Array[Npair] is abstract
519 redef class Nmembers_tail
522 var arr = n_members.pairs
528 redef class Nmembers_head
529 redef fun pairs do return [n_pair]
533 # The represented key.
534 private fun name: String do return n_string.to_nit_string
536 # The represented value.
537 private fun value: nullable Jsonable do return n_value.to_nit_object
540 redef class Nvalue_array
541 redef fun to_nit_object
543 var arr = new JsonArray
544 var elements = n_elements
545 if elements != null then
546 var items = elements.items
547 for item in items do arr.add(item.to_nit_object)
553 redef class Nelements
555 private fun items: Array[Nvalue] is abstract
558 redef class Nelements_tail
561 var items = n_elements.items
567 redef class Nelements_head
568 redef fun items do return [n_value]