lib: intro the abstract serialization module
[nit.git] / lib / 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 # Offers services to serialize a Nit objects to different persistent formats
18 module serialization
19
20 # Abstract serialization service to be sub-classed by specialized services.
21 interface Serializer
22 # Main method of this service, serialize the `object`
23 fun serialize(object: nullable Serializable) is abstract
24
25 # Serialize an object as a "possible" reference, depending of the service
26 fun serialize_reference(object: Serializable) is abstract
27
28 # Serialize an attribute, used by `Serializable::core_serialize_to`
29 fun serialize_attribute(name: String, value: nullable Object)
30 do
31 if value isa Serializable then
32 value.serialize_to_or_delay(self)
33 else if value == null then
34 serialize value
35 else
36 warn("argument {value.class_name}::{name} is not serializable.")
37 end
38 end
39
40 # Warn of problems and potential errors (such as if an attribute
41 # is not serializable)
42 fun warn(msg: String) do print "Serialization warning: {msg}"
43 end
44
45 # Instances of this class can be passed to `Serializer::serialize`
46 interface Serializable
47 # Full or true serialization
48 fun serialize_to(v: Serializer) do v.serialize(self)
49
50 # Body of the serialization of this class
51 # Can be redefed in sub classes and refinements
52 fun core_serialize_to(v: Serializer) do end
53
54 # Whether full serialization (calls `serialize_to`) or place only references
55 fun serialize_to_or_delay(v: Serializer) do v.serialize_reference(self)
56 end
57
58 # Instances of this class are not delayed and instead serialized immediately
59 # This applies mainly to `universal` types
60 interface DirectSerializable
61 super Serializable
62
63 redef fun serialize_to_or_delay(v) do serialize_to(v)
64 end
65
66 redef class Bool super DirectSerializable end
67 redef class Char super DirectSerializable end
68 redef class Int super DirectSerializable end
69 redef class Float super DirectSerializable end
70 redef class NativeString super DirectSerializable end
71 redef class String super DirectSerializable end