Merge: lib/github: use serialization
[nit.git] / lib / serialization / serialization.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Abstract services to serialize Nit objects to different formats
18 #
19 # This module declares the `serialize` annotation to mark Nit classes as serializable.
20 # For an introduction to this service, refer to the documentation of the `serialization` group.
21 # This documentation provides more technical information on interesting entitie of this module.
22 #
23 # Interesting entities for end users of serializable classes:
24 #
25 # * Serialize an instance subclass of `Serializable` with either
26 # `Serializer::serializable` and `Serializable::serialize`.
27 # * Deserialize an object using `Deserializer::deserialize`.
28 # The object type must the be checked with an `assert` or otherwise.
29 #
30 # Interesting entities to create custom serializable classes:
31 #
32 # * Subclass `Serializable` to declare a class as serializable and to customize
33 # the serialization and deserialization behavior.
34 # * Redefine `Serializable::core_serialize_to` to customize the serialization
35 # of the receiver class.
36 # * Redefine `Deserializer::deserialize_class` to customize the deserialization
37 # of a specific class by name.
38 #
39 # Interesting entities for serialization format:
40 #
41 # * Subclass `Serializer` and `Deserializer` with custom serices.
42 # * In `Serializer`, `serialize` and `serialize_reference` must be redefined.
43 # * In `Deserializer`; `deserialize`, `deserialize_attribute and
44 # `notify_of_creation` must be redefined.
45 module serialization is
46 new_annotation auto_serializable
47 new_annotation serialize
48 new_annotation noserialize
49 new_annotation serialize_as
50 end
51
52 # Abstract serialization service to be sub-classed by specialized services.
53 interface Serializer
54 # Entry point method of this service, serialize the `object`
55 #
56 # This method, and refinements, should handle `null` and probably
57 # use double dispatch to customize the bahavior per serializable objects.
58 fun serialize(object: nullable Serializable) is abstract
59
60 # Serialize an object, with full serialization or a simple reference
61 protected fun serialize_reference(object: Serializable) is abstract
62
63 # Serialize an attribute to compose a serializable object
64 #
65 # This method should be called from `Serializable::core_serialize_to`.
66 fun serialize_attribute(name: String, value: nullable Object)
67 do
68 if not try_to_serialize(value) then
69 warn("argument {name} of type {value.class_name} is not serializable.")
70 end
71 end
72
73 # Serialize `value` is possie, i.e. it is `Serializable` or `null`
74 fun try_to_serialize(value: nullable Object): Bool
75 do
76 if value isa Serializable then
77 value.serialize_to_or_delay(self)
78 else if value == null then
79 serialize value
80 else return false
81 return true
82 end
83
84 # Warn of problems and potential errors (such as if an attribute
85 # is not serializable)
86 fun warn(msg: String) do print "Serialization warning: {msg}"
87 end
88
89 # Abstract deserialization service
90 #
91 # The main service is `deserialize`.
92 abstract class Deserializer
93 # Deserialize and return an object, storing errors in the attribute `errors`
94 #
95 # This method behavior varies according to the implementation engines.
96 fun deserialize: nullable Object is abstract
97
98 # Deserialize the attribute with `name` from the object open for deserialization
99 #
100 # Internal method to be implemented by the engines.
101 fun deserialize_attribute(name: String): nullable Object is abstract
102
103 # Register a newly allocated object (even if not completely built)
104 #
105 # Internal method called by objects in creation, to be implemented by the engines.
106 fun notify_of_creation(new_object: Object) is abstract
107
108 # Deserialize the next available object as an instance of `class_name`
109 #
110 # Return the deserialized object on success and
111 # record in `errors` if `class_name` is unknown.
112 #
113 # This method should be redefined for each custom subclass of `Serializable`.
114 # All refinement should look for a precise `class_name` and call super
115 # on unsupported classes.
116 protected fun deserialize_class(class_name: String): nullable Object do
117 if class_name == "Error" then return new Error.from_deserializer(self)
118 return deserialize_class_intern(class_name)
119 end
120
121 # Generated service to deserialize the next available object as an instance of `class_name`
122 #
123 # Refinements to this method will be generated by the serialization phase.
124 # To avoid conflicts, there should not be any other refinements to this method.
125 # You can instead use `deserialize_class`.
126 protected fun deserialize_class_intern(class_name: String): nullable Object do
127 errors.add new Error("Deserialization Error: Doesn't know how to deserialize class \"{class_name}\"")
128 return null
129 end
130
131 # Should `self` keep trying to deserialize an object after an error?
132 #
133 # This behavior takes effect after each attribute deserialization with
134 # errors such as a missing attribute or the value is of the wrong type.
135 # If `keep_going`, the attribute will be skipped but the engine will
136 # deserialize the next attribute.
137 # If `not keep_going`, the engine stops deserializing right away.
138 #
139 # When at `true`, this may cause the accumulation of a lot of entries in `errors`.
140 #
141 # Default at `true`.
142 var keep_going: nullable Bool = null is writable
143
144 # Errors encountered in the last call to `deserialize`
145 var errors = new Array[Error]
146 end
147
148 # Deserialization got wrong attribute names
149 class AttributeTypeError
150 super Error
151
152 autoinit receiver, attribute_name, attribute, expected_type
153
154 # Parent object of the problematic attribute
155 var receiver: Object
156
157 # Name of the problematic attribute in `receiver`
158 var attribute_name: String
159
160 # Deserialized object that isn't of the `expected_type`
161 var attribute: nullable Object
162
163 # Name of the type expected for `attribute`
164 var expected_type: String
165
166 redef var message is lazy do
167 var attribute = attribute
168 var found_type = if attribute != null then attribute.class_name else "null"
169
170 return "Deserialization Error: {
171 }Wrong type on `{receiver.class_name}::{attribute_name}` expected `{expected_type}`, got `{found_type}`"
172 end
173 end
174
175 # Instances of this class can be passed to `Serializer::serialize`
176 interface Serializable
177 # Serialize `self` to `serializer`
178 #
179 # This is a shortcut to `Serializer::serialize`.
180 fun serialize_to(serializer: Serializer) do serializer.serialize(self)
181
182 # Actual serialization of `self` to `serializer`
183 #
184 # This writes the full data of `self` to `serializer`.
185 #
186 # This method can be redefined in sub classes and refinements.
187 # It should use `Serializer::serialize_attribute` to to register real or
188 # logical attributes.
189 #
190 # Any refinement should have its equivalent refinement of
191 # `Deserializer::deserialize_class` to support this custom deserialization.
192 fun core_serialize_to(serializer: Serializer) do end
193
194 # Accept references or force direct serialization (using `serialize_to`)
195 #
196 # The subclass change the default behavior, which will accept references,
197 # to force to always serialize copies of `self`.
198 private fun serialize_to_or_delay(v: Serializer) do v.serialize_reference(self)
199
200 # Create an instance of this class from the `deserializer`
201 #
202 # This constructor is refined by subclasses to correctly build their instances.
203 init from_deserializer(deserializer: Deserializer) is nosuper do end
204 end
205
206 redef interface Object
207 # Is `self` the same as `other` in a serialization context?
208 #
209 # Used to determine if an object has already been serialized.
210 fun is_same_serialized(other: nullable Object): Bool do return is_same_instance(other)
211
212 # Hash value use for serialization
213 #
214 # Used in combination with `is_same_serialized`. If two objects are the same
215 # in a serialization context, they must have the same `serialization_hash`.
216 fun serialization_hash: Int do return object_id
217 end
218
219 # Instances of this class are not delayed and instead serialized immediately
220 # This applies mainly to `universal` types
221 interface DirectSerializable
222 super Serializable
223
224 redef fun serialize_to_or_delay(v) do serialize_to(v)
225 end
226
227 redef class Bool super DirectSerializable end
228 redef class Char super DirectSerializable end
229 redef class Int super DirectSerializable end
230 redef class Float super DirectSerializable end
231 redef class NativeString super DirectSerializable end
232 redef class Text super DirectSerializable end
233 redef class SimpleCollection[E] super Serializable end
234 redef class Map[K, V] super Serializable end
235
236 redef class Couple[F, S]
237 super Serializable
238
239 redef init from_deserializer(v)
240 do
241 v.notify_of_creation self
242 var first = v.deserialize_attribute("first")
243 var second = v.deserialize_attribute("second")
244 init(first, second)
245 end
246
247 redef fun core_serialize_to(v)
248 do
249 v.serialize_attribute("first", first)
250 v.serialize_attribute("second", second)
251 end
252 end
253
254 redef class Ref[E]
255 super Serializable
256
257 redef init from_deserializer(v)
258 do
259 v.notify_of_creation self
260 var item = v.deserialize_attribute("item")
261 init item
262 end
263
264 redef fun core_serialize_to(v)
265 do
266 v.serialize_attribute("item", first)
267 end
268 end
269
270 redef class Error
271 super Serializable
272
273 redef init from_deserializer(v)
274 do
275 v.notify_of_creation self
276
277 var message = v.deserialize_attribute("message")
278 if not message isa String then message = ""
279 init message
280
281 var cause = v.deserialize_attribute("cause")
282 if cause isa nullable Error then self.cause = cause
283 end
284
285 redef fun core_serialize_to(v)
286 do
287 v.serialize_attribute("message", message)
288 v.serialize_attribute("cause", cause)
289 end
290 end