75863d9f4c885a877ac1e974205f5effdd27e44d
[nit.git] / src / frontend / serialization_phase.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2013 Guillaume Auger <jeho@resist.ca>
5 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
6 #
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
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
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.
18
19 # Phase generating methods to serialize Nit objects to different formats
20 module serialization_phase
21
22 private import parser_util
23 import modelize
24 private import annotation
25
26 redef class ToolContext
27 # Generate serialization and deserialization methods on `auto_serializable` annotated classes.
28 var serialization_phase_pre_model: Phase = new SerializationPhasePreModel(self, null)
29
30 # The second phase of the serialization
31 var serialization_phase_post_model: Phase = new SerializationPhasePostModel(self,
32 [modelize_class_phase, serialization_phase_pre_model])
33
34 private fun place_holder_type_name: String do return "PlaceHolderTypeWhichShouldNotExist"
35 end
36
37 # TODO add annotations on attributes (volatile, sensitive or do_not_serialize?)
38 private class SerializationPhasePreModel
39 super Phase
40
41 redef fun process_annotated_node(nclassdef, nat)
42 do
43 # Skip if we are not interested
44 if nat.n_atid.n_id.text != "auto_serializable" then return
45 if not nclassdef isa AStdClassdef then
46 toolcontext.error(nclassdef.location, "Syntax error: only a concrete class can be automatically serialized.")
47 return
48 end
49
50 # Add `super Serializable`
51 var sc = toolcontext.parse_superclass("Serializable")
52 sc.location = nat.location
53 nclassdef.n_propdefs.add sc
54
55 generate_serialization_method(nclassdef)
56
57 generate_deserialization_init(nclassdef)
58 end
59
60 redef fun process_nmodule(nmodule)
61 do
62 # Clear the cache of constructors to review before adding to it
63 nmodule.inits_to_retype.clear
64
65 # collect all classes
66 var auto_serializable_nclassdefs = new Array[AStdClassdef]
67 for nclassdef in nmodule.n_classdefs do
68 if nclassdef isa AStdClassdef and
69 not nclassdef.get_annotations("auto_serializable").is_empty then
70 auto_serializable_nclassdefs.add nclassdef
71 end
72 end
73
74 if not auto_serializable_nclassdefs.is_empty then
75 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
76 end
77 end
78
79 fun generate_serialization_method(nclassdef: AClassdef)
80 do
81 var npropdefs = nclassdef.n_propdefs
82
83 var code = new Array[String]
84 code.add "redef fun core_serialize_to(v)"
85 code.add "do"
86 code.add " super"
87
88 for attribute in npropdefs do if attribute isa AAttrPropdef then
89 var name = attribute.name
90 code.add " v.serialize_attribute(\"{name}\", {name})"
91 end
92
93 code.add "end"
94
95 # Create method Node and add it to the AST
96 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
97 end
98
99 # Add a constructor to the automated nclassdef
100 fun generate_deserialization_init(nclassdef: AClassdef)
101 do
102 var npropdefs = nclassdef.n_propdefs
103
104 var code = new Array[String]
105 code.add "init from_deserializer(v: Deserializer)"
106 code.add "do"
107 code.add " v.notify_of_creation self"
108
109 for attribute in npropdefs do if attribute isa AAttrPropdef then
110 var n_type = attribute.n_type
111 var type_name
112 if n_type == null then
113 # Use a place holder, we will replace it with the infered type after the model phases
114 type_name = toolcontext.place_holder_type_name
115 else
116 type_name = n_type.type_name
117 end
118 var name = attribute.name
119
120 code.add ""
121 code.add "\tvar {name} = v.deserialize_attribute(\"{name}\")"
122 code.add "\tassert {name} isa {type_name} else print \"Unsupported type for attribute '{name}', got '\{{name}.class_name\}' (ex {type_name})\""
123 code.add "\tself.{name} = {name}"
124 end
125
126 code.add "end"
127
128 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
129 npropdefs.add npropdef
130 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
131 end
132
133 # Added to the abstract serialization service
134 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
135 do
136 var code = new Array[String]
137
138 var deserializer_nclassdef = nmodule.deserializer_nclassdef
139 var deserializer_npropdef
140 if deserializer_nclassdef == null then
141 # create the class
142 code.add "redef class Deserializer"
143 deserializer_npropdef = null
144 else
145 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
146 end
147
148 if deserializer_npropdef == null then
149 # create the property
150 code.add " redef fun deserialize_class(name)"
151 code.add " do"
152 else
153 toolcontext.error(deserializer_npropdef.location, "Annotation error: you cannot define Deserializer::deserialize_class in a module where you use \"auto_serializable\".")
154 return
155 end
156
157 for nclassdef in nclassdefs do
158 var name = nclassdef.n_id.text
159 if nclassdef.n_formaldefs.is_empty then
160 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
161 end
162 end
163
164 code.add " return super"
165 code.add " end"
166
167 if deserializer_nclassdef == null then
168 code.add "end"
169 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
170 else
171 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
172 end
173 end
174 end
175
176 private class SerializationPhasePostModel
177 super Phase
178
179 redef fun process_nmodule(nmodule)
180 do
181 for npropdef in nmodule.inits_to_retype do
182 var v = new PreciseTypeVisitor(npropdef, npropdef.mpropdef.mclassdef, toolcontext)
183 npropdef.accept_precise_type_visitor v
184 end
185 end
186 end
187
188 # Visitor on generated constructors to replace the expected type of deserialized attributes
189 private class PreciseTypeVisitor
190 super Visitor
191
192 var npropdef: AMethPropdef
193 var mclassdef: MClassDef
194 var toolcontext: ToolContext
195
196 redef fun visit(n) do n.accept_precise_type_visitor(self)
197 end
198
199 redef class ANode
200 private fun accept_precise_type_visitor(v: PreciseTypeVisitor) do visit_all(v)
201 end
202
203 redef class AIsaExpr
204 redef fun accept_precise_type_visitor(v)
205 do
206 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
207
208 var attr_name = "_" + n_expr.collect_text
209 for mattrdef in v.mclassdef.mpropdefs do
210 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
211 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
212 n_type.replace_with new_ntype
213 break
214 end
215 end
216 end
217 end
218
219 redef class AAttrPropdef
220 private fun name: String
221 do
222 return n_id2.text
223 end
224 end
225
226 redef class AType
227 private fun type_name: String
228 do
229 var name = n_id.text
230
231 if n_kwnullable != null then name = "nullable {name}"
232
233 var types = n_types
234 if not types.is_empty then
235 var params = new Array[String]
236 for t in types do params.add(t.type_name)
237 return "{name}[{params.join(", ")}]"
238 else return name
239 end
240 end
241
242 redef class AModule
243 private fun deserializer_nclassdef: nullable AStdClassdef
244 do
245 for nclassdef in n_classdefs do
246 if nclassdef isa AStdClassdef and nclassdef.n_id.text == "Deserialization" then
247 return nclassdef
248 end
249 end
250
251 return null
252 end
253
254 private var inits_to_retype = new Array[AMethPropdef]
255 end
256
257 redef class AStdClassdef
258 private fun deserializer_npropdef: nullable AMethPropdef
259 do
260 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
261 var id = npropdef.n_methid
262 if id isa AIdMethid and id.n_id.text == "deserialize_class" then
263 return npropdef
264 end
265 end
266
267 return null
268 end
269 end