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
52 return buffer
.write_to_string
55 # Append the JSON representation of `self` to the specified buffer.
58 fun append_json
(buffer
: Buffer) do buffer
.append
(to_json
)
64 redef fun append_json
(buffer
) do
66 for i
in [0..self.length
[ do
70 else if char
== '\"' then
72 else if char == '\/' then
74 else if char < 16.ascii then
77 else if char == '\r' then
79 else if char == '\t' then
81 else if char == 0x0C.ascii then
83 else if char == 0x08.ascii then
86 buffer.append "\\u000
{char.ascii.to_hex}"
88 else if char < ' ' then
89 buffer.append "\\u00
{char.ascii.to_hex}"
97 # Encode `self` in JSON.
99 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
100 # "\"\\t\\\"http:\\/\\/example.com\\\"\\r\\n\\u0000\\\\\""
101 redef fun to_json do return to_json_by_append
103 # Parse `self` as JSON.
105 # If `self` is not a valid JSON document or contains an unsupported escape
106 # sequence, return a `JSONParseError`.
108 # Example with `JsonObject`:
110 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
111 # assert obj isa JsonObject
112 # assert obj["foo"] isa JsonObject
113 # assert obj["foo"].as(JsonObject)["bar"] == true
115 # Example with `JsonArray`:
117 # var arr = "[1, 2, 3]".parse_json
118 # assert arr isa JsonArray
119 # assert arr.length == 3
120 # assert arr.first == 1
121 # assert arr.last == 3
123 # Example with `String`:
125 # var str = "\"foo, bar, baz\"".parse_json
126 # assert str isa String
127 # assert str == "foo, bar, baz"
129 # Example of a syntaxic error:
131 # var bad = "\{foo: \"bar\"\}".parse_json
132 # assert bad isa JsonParseError
133 # assert bad.position.col_start == 2
134 fun parse_json: nullable Jsonable do
135 var lexer = new Lexer_json(to_s)
136 var parser = new Parser_json
137 var tokens = lexer.lex
138 parser.tokens.add_all(tokens)
139 var root_node = parser.parse
140 if root_node isa NStart then
141 return root_node.n_0.to_nit_object
142 else if root_node isa NError then
143 return new JsonParseError(root_node.message, root_node.position)
150 # Append the JSON representation of `jsonable` to `self`.
152 # Append `"null"` for `null`.
153 private fun append_json_of(jsonable: nullable Jsonable) do
154 if jsonable isa Jsonable then
155 append jsonable.to_json
165 # Encode `self` in JSON.
167 # assert 0.to_json == "0"
168 # assert (-42).to_json == "-42"
169 redef fun to_json do return self.to_s
175 # Encode `self` in JSON.
177 # Note: Because this method use `to_s`, it may lose precision.
180 # # Will not work as expected.
181 # # assert (-0.0).to_json == "-0.0"
183 # assert (.5).to_json == "0.5"
184 # assert (0.0).to_json == "0.0"
186 redef fun to_json do return self.to_s
192 # Encode `self` in JSON.
194 # assert true.to_json == "true"
195 # assert false.to_json == "false"
196 redef fun to_json do return self.to_s
199 # A map that can be translated into a JSON object.
200 interface JsonMapRead[K: String, V: nullable Jsonable]
204 redef fun append_json(buffer) do
208 append_json_entry(it, buffer)
211 append_json_entry(it, buffer)
218 # Encode `self` in JSON.
220 # var obj = new JsonObject
222 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
223 # obj = new JsonObject
225 # assert obj.to_json == "\{\"baz\":null\}"
226 redef fun to_json do return to_json_by_append
228 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
230 buffer.append iterator.key.to_json
232 buffer.append_json_of(iterator.item)
239 super JsonMapRead[String, nullable Jsonable]
240 super HashMap[String, nullable Jsonable]
243 # A sequence that can be translated into a JSON array.
244 class JsonSequenceRead[E: nullable Jsonable]
246 super SequenceRead[E]
248 redef fun append_json(buffer) do
252 append_json_entry(it, buffer)
255 append_json_entry(it, buffer)
262 # Encode `self` in JSON.
264 # var arr = new JsonArray.with_items("foo", null)
265 # assert arr.to_json == "[\"foo\",null]"
267 # assert arr.to_json =="[\"foo\"]"
269 # assert arr.to_json =="[]"
270 redef fun to_json do return to_json_by_append
272 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
274 buffer.append_json_of(iterator.item)
281 super JsonSequenceRead[nullable Jsonable]
282 super Array[nullable Jsonable]
285 redef class JsonParseError
288 # Get the JSON representation of `self`.
290 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
291 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
292 # "\"position\":\{" +
293 # "\"pos_start\":1,\"pos_end\":2," +
294 # "\"line_start\":3,\"line_end\":4," +
295 # "\"col_start\":5,\"col_end\":6" +
296 # "\},\"message\":\"foo\"\}"
298 return "\{\"error\":\"JsonParseError\"," +
299 "\"position\":{position.to_json}," +
300 "\"message\":{message.to_json}\}"
307 # Get the JSON representation of `self`.
309 # var pos = new Position(1, 2, 3, 4, 5, 6)
310 # assert pos.to_json == "\{" +
311 # "\"pos_start\":1,\"pos_end\":2," +
312 # "\"line_start\":3,\"line_end\":4," +
313 # "\"col_start\":5,\"col_end\":6" +
316 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
317 "\"line_start\":{line_start},\"line_end\":{line_end}," +
318 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
322 ################################################################################
326 # The represented value.
327 private fun to_nit_object: nullable Jsonable is abstract
330 redef class Nvalue_number
331 redef fun to_nit_object
333 var text = n_number.text
334 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
339 redef class Nvalue_string
340 redef fun to_nit_object do return n_string.to_nit_string
343 redef class Nvalue_true
344 redef fun to_nit_object do return true
347 redef class Nvalue_false
348 redef fun to_nit_object do return false
351 redef class Nvalue_null
352 redef fun to_nit_object do return null
356 # The represented string.
357 private fun to_nit_string: String do
358 var res = new FlatBuffer
360 while i < text.length - 1 do
367 else if char == 'f
' then
369 else if char == 'n
' then
371 else if char == 'r
' then
373 else if char == 't
' then
375 else if char == 'u
' then
376 var code = text.substring(i + 1, 4).to_hex
377 # TODO UTF-16 escaping is not supported yet.
385 # `"`, `/` or `\` => Keep `char` as-is.
390 return res.write_to_string
394 redef class Nvalue_object
395 redef fun to_nit_object do
396 var obj = new JsonObject
397 var members = n_members
398 if members != null then
399 var pairs = members.pairs
400 for pair in pairs do obj[pair.name] = pair.value
407 # All the key-value pairs.
408 private fun pairs: Array[Npair] is abstract
411 redef class Nmembers_tail
414 var arr = n_members.pairs
420 redef class Nmembers_head
421 redef fun pairs do return [n_pair]
425 # The represented key.
426 private fun name: String do return n_string.to_nit_string
428 # The represented value.
429 private fun value: nullable Jsonable do return n_value.to_nit_object
432 redef class Nvalue_array
433 redef fun to_nit_object
435 var arr = new JsonArray
436 var elements = n_elements
437 if elements != null then
438 var items = elements.items
439 for item in items do arr.add(item.to_nit_object)
445 redef class Nelements
447 private fun items: Array[Nvalue] is abstract
450 redef class Nelements_tail
453 var items = n_elements.items
459 redef class Nelements_head
460 redef fun items do return [n_value]