1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Services to read JSON: `from_json_string` and `JsonDeserializer`
16 module serialization_read
18 import serialization
::caching
19 private import serialization
::engine_tools
20 import serialization
::safe
23 private import string_parser
26 # Deserializer from a Json string.
27 class JsonDeserializer
28 super CachingDeserializer
29 super SafeDeserializer
31 # Json text to deserialize from.
32 private var text
: Text
34 # Root json object parsed from input text.
35 private var root
: nullable Object is noinit
37 # Depth-first path in the serialized object tree.
38 private var path
= new Array[Map[String, nullable Object]]
40 # Names of the attributes from the root to the object currently being deserialized
41 var attributes_path
= new Array[String]
43 # Last encountered object reference id.
46 var just_opened_id
: nullable Int = null
49 var root
= text
.parse_json
50 if root
isa Map[String, nullable Object] then path
.add
(root
)
54 redef fun deserialize_attribute
(name
, static_type
)
57 # The was a parsing error or the root is not an object
58 if not root
isa Error then
59 errors
.add
new Error("Deserialization Error: parsed JSON value is not an object.")
61 deserialize_attribute_missing
= false
65 var current
= path
.last
67 if not current
.keys
.has
(name
) then
68 # Let the generated code / caller of `deserialize_attribute` raise the missing attribute error
69 deserialize_attribute_missing
= true
73 var value
= current
[name
]
75 attributes_path
.add name
76 var res
= convert_object
(value
, static_type
)
79 deserialize_attribute_missing
= false
83 # This may be called multiple times by the same object from constructors
84 # in different nclassdef
85 redef fun notify_of_creation
(new_object
)
87 var id
= just_opened_id
88 if id
== null then return # Register `new_object` only once
89 cache
[id
] = new_object
92 # Convert the simple JSON `object` to a Nit object
93 private fun convert_object
(object
: nullable Object, static_type
: nullable String): nullable Object
95 if object
isa JsonParseError then
100 if object
isa Map[String, nullable Object] then
102 if object
.keys
.has
("__kind") then
103 kind
= object
["__kind"]
107 if kind
== "ref" then
108 if not object
.keys
.has
("__id") then
109 errors
.add
new Error("Deserialization Error: JSON object reference does not declare a `__id`.")
113 var id
= object
["__id"]
114 if not id
isa Int then
115 errors
.add
new Error("Deserialization Error: JSON object reference declares a non-integer `__id`.")
119 if not cache
.has_id
(id
) then
120 errors
.add
new Error("Deserialization Error: JSON object reference has an unknown `__id`.")
124 return cache
.object_for
(id
)
128 if kind
== "obj" or kind
== null then
130 if object
.keys
.has
("__id") then
133 if not id
isa Int then
134 errors
.add
new Error("Deserialization Error: JSON object declaration declares a non-integer `__id`.")
138 if cache
.has_id
(id
) then
139 errors
.add
new Error("Deserialization Error: JSON object with `__id` {id} is deserialized twice.")
144 var class_name
= object
.get_or_null
("__class")
145 if class_name
== null then
146 # Fallback to custom heuristic
147 class_name
= class_name_heuristic
(object
)
149 if class_name
== null and static_type
!= null then
150 # Fallack to the static type, strip the `nullable` prefix
151 class_name
= static_type
.strip_nullable
155 if class_name
== null then
156 errors
.add
new Error("Deserialization Error: JSON object declaration does not declare a `__class`.")
160 if not class_name
isa String then
161 errors
.add
new Error("Deserialization Error: JSON object declaration declares a non-string `__class`.")
165 if not accept
(class_name
, static_type
) then return null
171 var value
= deserialize_class
(class_name
)
172 just_opened_id
= null
181 if kind
== "char" then
182 if not object
.keys
.has
("__val") then
183 errors
.add
new Error("Deserialization Error: JSON `char` object does not declare a `__val`.")
187 var val
= object
["__val"]
189 if not val
isa String or val
.is_empty
then
190 errors
.add
new Error("Deserialization Error: JSON `char` object does not declare a single char in `__val`.")
194 return val
.chars
.first
198 if kind
== "byte" then
199 var val
= object
.get_or_null
("__val")
200 if not val
isa Int then
201 errors
.add
new Error("Serialization Error: JSON `byte` object does not declare an integer `__val`.")
208 errors
.add
new Error("Deserialization Error: JSON object has an unknown `__kind`.")
212 # Simple JSON array without serialization metadata
213 if object
isa Array[nullable Object] then
214 # Can we use the static type?
215 if static_type
!= null then
216 opened_array
= object
217 var value
= deserialize_class
(static_type
.strip_nullable
)
222 # This branch should rarely be used:
223 # when an array is the root object which is accepted but illegal in standard JSON,
224 # or in strange custom deserialization hacks.
226 var array
= new Array[nullable Object]
227 var types
= new HashSet[String]
228 var has_nullable
= false
230 var res
= convert_object
(e
)
234 types
.add res
.class_name
235 else has_nullable
= true
238 if types
.length
== 1 then
239 var array_type
= types
.first
242 if array_type
== "ASCIIFlatString" or array_type
== "UnicodeFlatString" then
244 typed_array
= new Array[nullable FlatString]
245 else typed_array
= new Array[FlatString]
246 else if array_type
== "Int" then
248 typed_array
= new Array[nullable Int]
249 else typed_array
= new Array[Int]
250 else if array_type
== "Float" then
252 typed_array
= new Array[nullable Float]
253 else typed_array
= new Array[Float]
255 # TODO support all array types when we separate the constructor
256 # `from_deserializer` from the filling of the items.
258 if not has_nullable
then
259 typed_array
= new Array[Object]
261 # Unsupported array type, return as `Array[nullable Object]`
266 assert typed_array
isa Array[nullable Object]
268 # Copy item to the new array
269 for e
in array
do typed_array
.add e
273 # Uninferrable type, return as `Array[nullable Object]`
277 if object
isa String and object
.length
== 1 and static_type
== "Char" then
278 # Char serialized as a JSON string
279 return object
.chars
.first
282 if object
isa Int and static_type
== "Byte" then
283 # Byte serialized as an integer
290 # Current array open for deserialization, used by `SimpleCollection::from_deserializer`
291 private var opened_array
: nullable Array[nullable Object] = null
293 redef fun deserialize
(static_type
)
296 return convert_object
(root
, static_type
)
299 # User customizable heuristic to infer the name of the Nit class to deserialize `json_object`
301 # This method is called only when deserializing an object without the metadata `__class`.
302 # Use the content of `json_object` to identify what Nit class it should be deserialized into.
303 # Or use `self.attributes_path` indicating where the deserialized object will be stored,
304 # is is less reliable as some objects don't have an associated attribute:
305 # the root/first deserialized object and collection elements.
307 # Return the class name as a `String` when it can be inferred,
308 # or `null` when the class name cannot be found.
310 # If a valid class name is returned, `json_object` will then be deserialized normally.
311 # So it must contain the attributes of the corresponding class, as usual.
324 # var related_data: MyData
327 # class MyJsonDeserializer
328 # super JsonDeserializer
330 # redef fun class_name_heuristic(json_object)
332 # # Infer the Nit class from the content of the JSON object.
333 # if json_object.keys.has("error") then return "MyError"
334 # if json_object.keys.has("data") then return "MyData"
336 # # Infer the Nit class from the attribute where it will be stored.
337 # # This line duplicates a previous line, and would only apply when
338 # # `MyData` is within a `MyError`.
339 # if attributes_path.not_empty and attributes_path.last == "related_data" then return "MyData"
345 # var json = """{"data": "some data"}"""
346 # var deserializer = new MyJsonDeserializer(json)
347 # var deserialized = deserializer.deserialize
348 # assert deserializer.errors.is_empty
349 # assert deserialized isa MyData
351 # json = """{"error": "some error message",
352 # "related_data": {"data": "some other data"}}"""
353 # deserializer = new MyJsonDeserializer(json)
354 # deserialized = deserializer.deserialize
355 # assert deserializer.errors.is_empty
356 # assert deserialized isa MyError
358 protected fun class_name_heuristic
(json_object
: Map[String, nullable Object]): nullable String
366 # Deserialize a `nullable Object` from this JSON formatted string
368 # Warning: Deserialization errors are reported with `print_error` and
369 # may be returned as a partial object or as `null`.
371 # This method is not appropriate when errors need to be handled programmatically,
372 # manually use a `JsonDeserializer` in such cases.
373 fun from_json_string
: nullable Object
375 var deserializer
= new JsonDeserializer(self)
376 var res
= deserializer
.deserialize
377 if deserializer
.errors
.not_empty
then
378 print_error
"Deserialization Errors: {deserializer.errors.join(", ")}"
384 redef class SimpleCollection[E
]
385 redef init from_deserializer
(v
)
388 if v
isa JsonDeserializer then
389 v
.notify_of_creation
self
392 var open_array
: nullable SequenceRead[nullable Object] = v
.opened_array
393 if open_array
== null then
395 var arr
= v
.path
.last
.get_or_null
("__items")
396 if not arr
isa SequenceRead[nullable Object] then
397 # If there is nothing, we consider that it is an empty collection.
398 if arr
!= null then v
.errors
.add
new Error("Deserialization Error: invalid format in {self.class_name}")
404 # Name of the dynamic name of E
405 var items_type_name
= (new GetName[E
]).to_s
408 for o
in open_array
do
409 var obj
= v
.convert_object
(o
, items_type_name
)
412 else v
.errors
.add
new AttributeTypeError(self, "items", obj
, items_type_name
)
418 redef class Map[K
, V
]
419 redef init from_deserializer
(v
)
423 if v
isa JsonDeserializer then
424 v
.notify_of_creation
self
427 var keys_type_name
= (new GetName[K
]).to_s
428 var values_type_name
= (new GetName[V
]).to_s
430 var length
= v
.deserialize_attribute
("__length")
431 var keys
= v
.path
.last
.get_or_null
("__keys")
432 var values
= v
.path
.last
.get_or_null
("__values")
434 if keys
== null and values
== null then
435 # Fallback to a plain object
436 for key
, value_src
in v
.path
.last
do
438 var value
= v
.convert_object
(value_src
, values_type_name
)
440 if not key
isa K
then
441 v
.errors
.add
new AttributeTypeError(self, "keys", key
, keys_type_name
)
445 if not value
isa V
then
446 v
.errors
.add
new AttributeTypeError(self, "values", value
, values_type_name
)
456 if length
== null and keys
isa SequenceRead[nullable Object] then length
= keys
.length
459 if not length
isa Int or length
< 0 or
460 not keys
isa SequenceRead[nullable Object] or
461 not values
isa SequenceRead[nullable Object] or
462 keys
.length
!= values
.length
or length
!= keys
.length
then
464 # If there is nothing or length == 0, we consider that it is an empty Map.
465 if (length
!= null and length
!= 0) or keys
!= null or values
!= null then
466 v
.errors
.add
new Error("Deserialization Error: invalid format in {self.class_name}")
471 # First, convert all keys to follow the order of the serialization
472 var converted_keys
= new Array[K
]
473 for i
in length
.times
do
474 var key
= v
.convert_object
(keys
[i
], keys_type_name
)
476 if not key
isa K
then
477 v
.errors
.add
new AttributeTypeError(self, "keys", key
, keys_type_name
)
481 converted_keys
.add key
484 # Then convert the values and build the map
485 for i
in length
.times
do
486 var key
= converted_keys
[i
]
487 var value
= v
.convert_object
(values
[i
], values_type_name
)
489 if not value
isa V
then
490 v
.errors
.add
new AttributeTypeError(self, "values", value
, values_type_name
)
495 v
.errors
.add
new Error("Deserialization Error: duplicated key '{key or else "null"}' in {self.class_name}, previous value overwritten")
507 # Class inheritance graph as a `POSet[String]` serialized to JSON
508 private fun class_inheritance_metamodel_json
: CString is intern
511 redef var class_inheritance_metamodel
is lazy
do
512 var engine
= new JsonDeserializer(class_inheritance_metamodel_json
.to_s
)
513 engine
.check_subtypes
= false
514 engine
.whitelist
.add_all
(
515 ["String", "POSet[String]", "POSetElement[String]",
516 "HashSet[String]", "HashMap[String, POSetElement[String]]"])
518 var poset
= engine
.deserialize
519 if engine
.errors
.not_empty
then
520 print_error
"Deserialization errors in class_inheritance_metamodel:"
521 print_error engine
.errors
.join
("\n* ")
522 return new POSet[String]
525 if poset
isa POSet[String] then return poset
526 return new POSet[String]