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 RopeBuffer
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 redef fun append_json
(buffer
) do
94 for i
in [0 .. self.length
[ do
98 else if char
== '\"' then
100 else if char == '\/' then
102 else if char < ' ' then
105 else if char == '\r' then
107 else if char == '\t' then
109 else if char == 0x0C.code_point then
111 else if char == 0x08.code_point then
114 buffer.append char.escape_to_utf16
123 # Encode `self` in JSON.
126 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
127 # "\"\\t\\\"http:\\/\\/example.com\\\"\\r\\n\\u0000\\\\\""
129 redef fun to_json do return to_json_by_append
131 # Parse `self` as JSON.
133 # If `self` is not a valid JSON document or contains an unsupported escape
134 # sequence, return a `JSONParseError`.
136 # Example with `JsonObject`:
138 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
139 # assert obj isa JsonObject
140 # assert obj["foo"] isa JsonObject
141 # assert obj["foo"].as(JsonObject)["bar"] == true
143 # Example with `JsonArray`:
145 # var arr = "[1, 2, 3]".parse_json
146 # assert arr isa JsonArray
147 # assert arr.length == 3
148 # assert arr.first == 1
149 # assert arr.last == 3
151 # Example with `String`:
153 # var str = "\"foo, bar, baz\"".parse_json
154 # assert str isa String
155 # assert str == "foo, bar, baz"
157 # Example of a syntaxic error:
159 # var bad = "\{foo: \"bar\"\}".parse_json
160 # assert bad isa JsonParseError
161 # assert bad.position.col_start == 2
162 fun parse_json: nullable Jsonable do
163 var lexer = new Lexer_json(to_s)
164 var parser = new Parser_json
165 var tokens = lexer.lex
166 parser.tokens.add_all(tokens)
167 var root_node = parser.parse
168 if root_node isa NStart then
169 return root_node.n_0.to_nit_object
170 else if root_node isa NError then
171 return new JsonParseError(root_node.message, root_node.position)
178 # Append the JSON representation of `jsonable` to `self`.
180 # Append `"null"` for `null`.
181 private fun append_json_of(jsonable: nullable Jsonable) do
182 if jsonable isa Jsonable then
183 append jsonable.to_json
193 # Encode `self` in JSON.
195 # assert 0.to_json == "0"
196 # assert (-42).to_json == "-42"
197 redef fun to_json do return self.to_s
203 # Encode `self` in JSON.
205 # Note: Because this method use `to_s`, it may lose precision.
208 # # Will not work as expected.
209 # # assert (-0.0).to_json == "-0.0"
211 # assert (.5).to_json == "0.5"
212 # assert (0.0).to_json == "0.0"
214 redef fun to_json do return self.to_s
220 # Encode `self` in JSON.
222 # assert true.to_json == "true"
223 # assert false.to_json == "false"
224 redef fun to_json do return self.to_s
227 # A map that can be translated into a JSON object.
228 interface JsonMapRead[K: String, V: nullable Jsonable]
232 redef fun append_json(buffer) do
236 append_json_entry(it, buffer)
239 append_json_entry(it, buffer)
246 # Encode `self` in JSON.
248 # var obj = new JsonObject
250 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
251 # obj = new JsonObject
253 # assert obj.to_json == "\{\"baz\":null\}"
254 redef fun to_json do return to_json_by_append
256 redef fun pretty_json_visit(buffer, indent) do
261 buffer.append "\t" * indent
262 buffer.append "\"{k}\": "
263 if v isa JsonObject or v isa JsonArray then
264 v.pretty_json_visit(buffer, indent)
266 buffer.append v.to_json
268 if i < length - 1 then
275 buffer.append "\t" * indent
279 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
281 buffer.append iterator.key.to_json
283 buffer.append_json_of(iterator.item)
290 super JsonMapRead[String, nullable Jsonable]
291 super HashMap[String, nullable Jsonable]
294 # A sequence that can be translated into a JSON array.
295 class JsonSequenceRead[E: nullable Jsonable]
297 super SequenceRead[E]
299 redef fun append_json(buffer) do
303 append_json_entry(it, buffer)
306 append_json_entry(it, buffer)
313 # Encode `self` in JSON.
315 # var arr = new JsonArray.with_items("foo", null)
316 # assert arr.to_json == "[\"foo\",null]"
318 # assert arr.to_json =="[\"foo\"]"
320 # assert arr.to_json =="[]"
321 redef fun to_json do return to_json_by_append
323 redef fun pretty_json_visit(buffer, indent) do
327 if v isa JsonObject or v isa JsonArray then
328 v.pretty_json_visit(buffer, indent)
330 buffer.append v.to_json
332 if i < length - 1 then buffer.append ", "
338 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
340 buffer.append_json_of(iterator.item)
347 super JsonSequenceRead[nullable Jsonable]
348 super Array[nullable Jsonable]
351 redef class JsonParseError
354 # Get the JSON representation of `self`.
357 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
358 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
359 # "\"position\":\{" +
360 # "\"pos_start\":1,\"pos_end\":2," +
361 # "\"line_start\":3,\"line_end\":4," +
362 # "\"col_start\":5,\"col_end\":6" +
363 # "\},\"message\":\"foo\"\}"
366 return "\{\"error\":\"JsonParseError\"," +
367 "\"position\":{position.to_json}," +
368 "\"message\":{message.to_json}\}"
375 # Get the JSON representation of `self`.
378 # var pos = new Position(1, 2, 3, 4, 5, 6)
379 # assert pos.to_json == "\{" +
380 # "\"pos_start\":1,\"pos_end\":2," +
381 # "\"line_start\":3,\"line_end\":4," +
382 # "\"col_start\":5,\"col_end\":6" +
386 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
387 "\"line_start\":{line_start},\"line_end\":{line_end}," +
388 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
392 ################################################################################
396 # The represented value.
397 private fun to_nit_object: nullable Jsonable is abstract
400 redef class Nvalue_number
401 redef fun to_nit_object
403 var text = n_number.text
404 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
409 redef class Nvalue_string
410 redef fun to_nit_object do return n_string.to_nit_string
413 redef class Nvalue_true
414 redef fun to_nit_object do return true
417 redef class Nvalue_false
418 redef fun to_nit_object do return false
421 redef class Nvalue_null
422 redef fun to_nit_object do return null
426 # The represented string.
427 private fun to_nit_string: String do
430 while i < text.length - 1 do
436 char = 0x08.code_point
437 else if char == 'f
' then
438 char = 0x0C.code_point
439 else if char == 'n
' then
441 else if char == 'r
' then
443 else if char == 't
' then
445 else if char == 'u
' then
446 var escape = new Buffer
448 var code = text.substring(i + 1, 4)
451 if hx >= 0xD800 and hx <= 0xDFFF then
452 var lostr = text.substring(i + 7, 4)
453 if lostr.length < 4 then
455 escape.append "\\uFFFD"
463 char = escape.from_utf16_escape
465 # `"`, `/` or `\` => Keep `char` as-is.
474 redef class Nvalue_object
475 redef fun to_nit_object do
476 var obj = new JsonObject
477 var members = n_members
478 if members != null then
479 var pairs = members.pairs
480 for pair in pairs do obj[pair.name] = pair.value
487 # All the key-value pairs.
488 private fun pairs: Array[Npair] is abstract
491 redef class Nmembers_tail
494 var arr = n_members.pairs
500 redef class Nmembers_head
501 redef fun pairs do return [n_pair]
505 # The represented key.
506 private fun name: String do return n_string.to_nit_string
508 # The represented value.
509 private fun value: nullable Jsonable do return n_value.to_nit_object
512 redef class Nvalue_array
513 redef fun to_nit_object
515 var arr = new JsonArray
516 var elements = n_elements
517 if elements != null then
518 var items = elements.items
519 for item in items do arr.add(item.to_nit_object)
525 redef class Nelements
527 private fun items: Array[Nvalue] is abstract
530 redef class Nelements_tail
533 var items = n_elements.items
539 redef class Nelements_head
540 redef fun items do return [n_value]