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
)
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)
83 return res
.write_to_string
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 < 16.ascii then
105 else if char == '\r' then
107 else if char == '\t' then
109 else if char == 0x0C.ascii then
111 else if char == 0x08.ascii then
114 buffer.append "\\u000
{char.ascii.to_hex}"
116 else if char < ' ' then
117 buffer.append "\\u00
{char.ascii.to_hex}"
125 # Encode `self` in JSON.
128 # assert "\t\"http://example.com\"\r\n\0\\".to_json ==
129 # "\"\\t\\\"http:\\/\\/example.com\\\"\\r\\n\\u0000\\\\\""
131 redef fun to_json do return to_json_by_append
133 # Parse `self` as JSON.
135 # If `self` is not a valid JSON document or contains an unsupported escape
136 # sequence, return a `JSONParseError`.
138 # Example with `JsonObject`:
140 # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
141 # assert obj isa JsonObject
142 # assert obj["foo"] isa JsonObject
143 # assert obj["foo"].as(JsonObject)["bar"] == true
145 # Example with `JsonArray`:
147 # var arr = "[1, 2, 3]".parse_json
148 # assert arr isa JsonArray
149 # assert arr.length == 3
150 # assert arr.first == 1
151 # assert arr.last == 3
153 # Example with `String`:
155 # var str = "\"foo, bar, baz\"".parse_json
156 # assert str isa String
157 # assert str == "foo, bar, baz"
159 # Example of a syntaxic error:
161 # var bad = "\{foo: \"bar\"\}".parse_json
162 # assert bad isa JsonParseError
163 # assert bad.position.col_start == 2
164 fun parse_json: nullable Jsonable do
165 var lexer = new Lexer_json(to_s)
166 var parser = new Parser_json
167 var tokens = lexer.lex
168 parser.tokens.add_all(tokens)
169 var root_node = parser.parse
170 if root_node isa NStart then
171 return root_node.n_0.to_nit_object
172 else if root_node isa NError then
173 return new JsonParseError(root_node.message, root_node.position)
180 # Append the JSON representation of `jsonable` to `self`.
182 # Append `"null"` for `null`.
183 private fun append_json_of(jsonable: nullable Jsonable) do
184 if jsonable isa Jsonable then
185 append jsonable.to_json
195 # Encode `self` in JSON.
197 # assert 0.to_json == "0"
198 # assert (-42).to_json == "-42"
199 redef fun to_json do return self.to_s
205 # Encode `self` in JSON.
207 # Note: Because this method use `to_s`, it may lose precision.
210 # # Will not work as expected.
211 # # assert (-0.0).to_json == "-0.0"
213 # assert (.5).to_json == "0.5"
214 # assert (0.0).to_json == "0.0"
216 redef fun to_json do return self.to_s
222 # Encode `self` in JSON.
224 # assert true.to_json == "true"
225 # assert false.to_json == "false"
226 redef fun to_json do return self.to_s
229 # A map that can be translated into a JSON object.
230 interface JsonMapRead[K: String, V: nullable Jsonable]
234 redef fun append_json(buffer) do
238 append_json_entry(it, buffer)
241 append_json_entry(it, buffer)
248 # Encode `self` in JSON.
250 # var obj = new JsonObject
252 # assert obj.to_json == "\{\"foo\":\"bar\"\}"
253 # obj = new JsonObject
255 # assert obj.to_json == "\{\"baz\":null\}"
256 redef fun to_json do return to_json_by_append
258 redef fun pretty_json_visit(buffer, indent) do
263 buffer.append "\t" * indent
264 buffer.append "\"{k}\": "
265 if v isa JsonObject or v isa JsonArray then
266 v.pretty_json_visit(buffer, indent)
268 buffer.append v.to_json
270 if i < length - 1 then
277 buffer.append "\t" * indent
281 private fun append_json_entry(iterator: MapIterator[String, nullable Jsonable],
283 buffer.append iterator.key.to_json
285 buffer.append_json_of(iterator.item)
292 super JsonMapRead[String, nullable Jsonable]
293 super HashMap[String, nullable Jsonable]
296 # A sequence that can be translated into a JSON array.
297 class JsonSequenceRead[E: nullable Jsonable]
299 super SequenceRead[E]
301 redef fun append_json(buffer) do
305 append_json_entry(it, buffer)
308 append_json_entry(it, buffer)
315 # Encode `self` in JSON.
317 # var arr = new JsonArray.with_items("foo", null)
318 # assert arr.to_json == "[\"foo\",null]"
320 # assert arr.to_json =="[\"foo\"]"
322 # assert arr.to_json =="[]"
323 redef fun to_json do return to_json_by_append
325 redef fun pretty_json_visit(buffer, indent) do
329 if v isa JsonObject or v isa JsonArray then
330 v.pretty_json_visit(buffer, indent)
332 buffer.append v.to_json
334 if i < length - 1 then buffer.append ", "
340 private fun append_json_entry(iterator: Iterator[nullable Jsonable],
342 buffer.append_json_of(iterator.item)
349 super JsonSequenceRead[nullable Jsonable]
350 super Array[nullable Jsonable]
353 redef class JsonParseError
356 # Get the JSON representation of `self`.
359 # var err = new JsonParseError("foo", new Position(1, 2, 3, 4, 5, 6))
360 # assert err.to_json == "\{\"error\":\"JsonParseError\"," +
361 # "\"position\":\{" +
362 # "\"pos_start\":1,\"pos_end\":2," +
363 # "\"line_start\":3,\"line_end\":4," +
364 # "\"col_start\":5,\"col_end\":6" +
365 # "\},\"message\":\"foo\"\}"
368 return "\{\"error\":\"JsonParseError\"," +
369 "\"position\":{position.to_json}," +
370 "\"message\":{message.to_json}\}"
377 # Get the JSON representation of `self`.
380 # var pos = new Position(1, 2, 3, 4, 5, 6)
381 # assert pos.to_json == "\{" +
382 # "\"pos_start\":1,\"pos_end\":2," +
383 # "\"line_start\":3,\"line_end\":4," +
384 # "\"col_start\":5,\"col_end\":6" +
388 return "\{\"pos_start\":{pos_start},\"pos_end\":{pos_end}," +
389 "\"line_start\":{line_start},\"line_end\":{line_end}," +
390 "\"col_start\":{col_start},\"col_end\":{col_end}\}"
394 ################################################################################
398 # The represented value.
399 private fun to_nit_object: nullable Jsonable is abstract
402 redef class Nvalue_number
403 redef fun to_nit_object
405 var text = n_number.text
406 if text.chars.has('.') or text.chars.has('e
') or text.chars.has('E
') then return text.to_f
411 redef class Nvalue_string
412 redef fun to_nit_object do return n_string.to_nit_string
415 redef class Nvalue_true
416 redef fun to_nit_object do return true
419 redef class Nvalue_false
420 redef fun to_nit_object do return false
423 redef class Nvalue_null
424 redef fun to_nit_object do return null
428 # The represented string.
429 private fun to_nit_string: String do
430 var res = new FlatBuffer
432 while i < text.length - 1 do
439 else if char == 'f
' then
441 else if char == 'n
' then
443 else if char == 'r
' then
445 else if char == 't
' then
447 else if char == 'u
' then
448 var code = text.substring(i + 1, 4).to_hex
449 # TODO UTF-16 escaping is not supported yet.
457 # `"`, `/` or `\` => Keep `char` as-is.
462 return res.write_to_string
466 redef class Nvalue_object
467 redef fun to_nit_object do
468 var obj = new JsonObject
469 var members = n_members
470 if members != null then
471 var pairs = members.pairs
472 for pair in pairs do obj[pair.name] = pair.value
479 # All the key-value pairs.
480 private fun pairs: Array[Npair] is abstract
483 redef class Nmembers_tail
486 var arr = n_members.pairs
492 redef class Nmembers_head
493 redef fun pairs do return [n_pair]
497 # The represented key.
498 private fun name: String do return n_string.to_nit_string
500 # The represented value.
501 private fun value: nullable Jsonable do return n_value.to_nit_object
504 redef class Nvalue_array
505 redef fun to_nit_object
507 var arr = new JsonArray
508 var elements = n_elements
509 if elements != null then
510 var items = elements.items
511 for item in items do arr.add(item.to_nit_object)
517 redef class Nelements
519 private fun items: Array[Nvalue] is abstract
522 redef class Nelements_tail
525 var items = n_elements.items
531 redef class Nelements_head
532 redef fun items do return [n_value]