bb578fdd89152992b2809b89555341c936d9d3b5
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 # Append the JSON representation of `self` to the specified buffer.
40 fun append_json
(buffer
: Buffer) do
41 buffer
.append
(to_json
)
48 redef fun append_json
(buffer
) do
50 for i
in [0..self.length
[ do
54 else if char
== '\"' then
56 else if char == '\/' then
58 else if char < 16.ascii then
61 else if char == '\r' then
63 else if char == '\t' then
65 else if char == 0x0C.ascii then
67 else if char == 0x08.ascii then
70 buffer.append "\\u000
{char.ascii.to_hex}"
72 else if char < ' ' then
73 buffer.append "\\u00
{char.ascii.to_hex}"
81 # Encode `self` in JSON.
83 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
84 # "\"\\t\\\"http:\\/\\/example.com\\\"\\r\\n\\u0000\\\\\""
86 var buffer = new FlatBuffer
88 return buffer.write_to_string
91 # Parse `self` as JSON.
93 # If `self` is not a valid JSON document or contains an unsupported escape
94 # sequence, return a `JSONParseError`.
96 # Example with `JsonObject`:
98 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
99 # assert obj isa JsonObject
100 # assert obj["foo"] isa JsonObject
101 # assert obj["foo"].as(JsonObject)["bar"] == true
103 # Example with `JsonArray`:
105 # var arr = "[1, 2, 3]".parse_json
106 # assert arr isa JsonArray
107 # assert arr.length == 3
108 # assert arr.first == 1
109 # assert arr.last == 3
111 # Example with `String`:
113 # var str = "\"foo, bar, baz\"".parse_json
114 # assert str isa String
115 # assert str == "foo, bar, baz"
117 # Example of a syntaxic error:
119 # var bad = "\{foo: \"bar\"\}".parse_json
120 # assert bad isa JsonParseError
121 # assert bad.position.col_start == 2
122 fun parse_json: nullable Jsonable do
123 var lexer = new Lexer_json(to_s)
124 var parser = new Parser_json
125 var tokens = lexer.lex
126 parser.tokens.add_all(tokens)
127 var root_node = parser.parse
128 if root_node isa NStart then
129 return root_node.n_0.to_nit_object
130 else if root_node isa NError then
131 return new JsonParseError(root_node.message, root_node.position)
138 # Append the JSON representation of `jsonable` to `self`.
140 # Append `"null"` for `null`.
141 private fun append_json_of(jsonable: nullable Jsonable) do
142 if jsonable isa Jsonable then
143 append jsonable.to_json
153 # Encode `self` in JSON.
155 # assert 0.to_json == "0"
156 # assert (-42).to_json == "-42"
157 redef fun to_json do return self.to_s
163 # Encode `self` in JSON.
165 # Note: Because this method use `to_s`, it may lose precision.
168 # # Will not work as expected.
169 # # assert (-0.0).to_json == "-0.0"
171 # assert (.5).to_json == "0.5"
172 # assert (0.0).to_json == "0.0"
174 redef fun to_json do return self.to_s
180 # Encode `self` in JSON.
182 # assert true.to_json == "true"
183 # assert false.to_json == "false"
184 redef fun to_json do return self.to_s
187 # A map that can be translated into a JSON object.
188 interface JsonMapRead[K: String, V: nullable Jsonable]
192 redef fun append_json(buffer) do
196 append_json_entry(it, buffer)
199 append_json_entry(it, buffer)
206 # Encode `self` in JSON.
208 # var obj = new JsonObject
210 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
211 # obj = new JsonObject
213 # assert obj.to_json == "\{\"baz\":null\}"
215 var buffer = new FlatBuffer
217 return buffer.write_to_string
220 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
222 buffer.append iterator.key.to_json
224 buffer.append_json_of(iterator.item)
231 super JsonMapRead[String, nullable Jsonable]
232 super HashMap[String, nullable Jsonable]
235 # A sequence that can be translated into a JSON array.
236 class JsonSequenceRead[E: nullable Jsonable]
238 super SequenceRead[E]
240 redef fun append_json(buffer) do
244 append_json_entry(it, buffer)
247 append_json_entry(it, buffer)
254 # Encode `self` in JSON.
256 # var arr = new JsonArray.with_items("foo", null)
257 # assert arr.to_json == "[\"foo\",null]"
259 # assert arr.to_json =="[\"foo\"]"
261 # assert arr.to_json =="[]"
263 var buffer = new FlatBuffer
265 return buffer.write_to_string
268 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
270 buffer.append_json_of(iterator.item)
277 super JsonSequenceRead[nullable Jsonable]
278 super Array[nullable Jsonable]
281 redef class JsonParseError
284 # Get the JSON representation of `self`.
286 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
287 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
288 # "\"position\":\{" +
289 # "\"pos_start\":1,\"pos_end\":2," +
290 # "\"line_start\":3,\"line_end\":4," +
291 # "\"col_start\":5,\"col_end\":6" +
292 # "\},\"message\":\"foo\"\}"
294 return "\{\"error\":\"JsonParseError\"," +
295 "\"position\":{position.to_json}," +
296 "\"message\":{message.to_json}\}"
303 # Get the JSON representation of `self`.
305 # var pos = new Position(1, 2, 3, 4, 5, 6)
306 # assert pos.to_json == "\{" +
307 # "\"pos_start\":1,\"pos_end\":2," +
308 # "\"line_start\":3,\"line_end\":4," +
309 # "\"col_start\":5,\"col_end\":6" +
312 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
313 "\"line_start\":{line_start},\"line_end\":{line_end}," +
314 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
318 ################################################################################
322 # The represented value.
323 private fun to_nit_object: nullable Jsonable is abstract
326 redef class Nvalue_number
327 redef fun to_nit_object
329 var text = n_number.text
330 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
335 redef class Nvalue_string
336 redef fun to_nit_object do return n_string.to_nit_string
339 redef class Nvalue_true
340 redef fun to_nit_object do return true
343 redef class Nvalue_false
344 redef fun to_nit_object do return false
347 redef class Nvalue_null
348 redef fun to_nit_object do return null
352 # The represented string.
353 private fun to_nit_string: String do
354 var res = new FlatBuffer
356 while i < text.length - 1 do
363 else if char == 'f
' then
365 else if char == 'n
' then
367 else if char == 'r
' then
369 else if char == 't
' then
371 else if char == 'u
' then
372 var code = text.substring(i + 1, 4).to_hex
373 # TODO UTF-16 escaping is not supported yet.
381 # `"`, `/` or `\` => Keep `char` as-is.
386 return res.write_to_string
390 redef class Nvalue_object
391 redef fun to_nit_object do
392 var obj = new JsonObject
393 var members = n_members
394 if members != null then
395 var pairs = members.pairs
396 for pair in pairs do obj[pair.name] = pair.value
403 # All the key-value pairs.
404 private fun pairs: Array[Npair] is abstract
407 redef class Nmembers_tail
410 var arr = n_members.pairs
416 redef class Nmembers_head
417 redef fun pairs do return [n_pair]
421 # The represented key.
422 private fun name: String do return n_string.to_nit_string
424 # The represented value.
425 private fun value: nullable Jsonable do return n_value.to_nit_object
428 redef class Nvalue_array
429 redef fun to_nit_object
431 var arr = new JsonArray
432 var elements = n_elements
433 if elements != null then
434 var items = elements.items
435 for item in items do arr.add(item.to_nit_object)
441 redef class Nelements
443 private fun items: Array[Nvalue] is abstract
446 redef class Nelements_tail
449 var items = n_elements.items
455 redef class Nelements_head
456 redef fun items do return [n_value]