frontend serialization: do not generate from_deserializer if it exists locally
[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 redef class ANode
38 # Is this node annotated to be made serializable?
39 private fun is_serialize: Bool do return false
40
41 # Is this node annotated to not be made serializable?
42 private fun is_noserialize: Bool do return false
43
44 private fun accept_precise_type_visitor(v: PreciseTypeVisitor) do visit_all(v)
45 end
46
47 redef class ADefinition
48
49 redef fun is_serialize do
50 return get_annotations("serialize").not_empty or
51 get_annotations("auto_serializable").not_empty
52 end
53
54 redef fun is_noserialize do
55 return get_annotations("noserialize").not_empty
56 end
57 end
58
59 private class SerializationPhasePreModel
60 super Phase
61
62 redef fun process_annotated_node(node, nat)
63 do
64 # Skip if we are not interested
65 var text = nat.n_atid.n_id.text
66 var serialize = text == "auto_serializable" or text == "serialize"
67 var noserialize = text == "noserialize"
68 if not (serialize or noserialize) then return
69
70 # Check legality of annotation
71 if node isa AModuledecl then
72 if noserialize then toolcontext.error(node.location, "Syntax Error: superfluous use of `{text}`, by default a module is `{text}`")
73 return
74 else if not (node isa AStdClassdef or node isa AAttrPropdef) then
75 toolcontext.error(node.location,
76 "Syntax Error: only a class, a module or an attribute can be annotated with `{text}`.")
77 return
78 else if serialize and node.is_noserialize then
79 toolcontext.error(node.location,
80 "Syntax Error: an entity cannot be both `{text}` and `noserialize`.")
81 return
82 else if node.as(Prod).get_annotations(text).length > 1 then
83 toolcontext.warning(node.location, "useless-{text}",
84 "Warning: duplicated annotation `{text}`.")
85 end
86
87 # Check the `serialize` state of the parent
88 if not node isa AModuledecl then
89 var up_serialize = false
90 var up: nullable ANode = node
91 loop
92 up = up.parent
93 if up == null then
94 break
95 else if up.is_serialize then
96 up_serialize = true
97 break
98 else if up.is_noserialize then
99 break
100 end
101 end
102
103 # Check for useless double declarations
104 if serialize and up_serialize then
105 toolcontext.warning(node.location, "useless-serialize",
106 "Warning: superfluous use of `{text}`.")
107 else if noserialize and not up_serialize then
108 toolcontext.warning(node.location, "useless-noserialize",
109 "Warning: superfluous use of `{text}`.")
110 end
111 end
112 end
113
114 redef fun process_nclassdef(nclassdef)
115 do
116 if not nclassdef isa AStdClassdef then return
117
118 var serialize_by_default = nclassdef.how_serialize
119
120 if serialize_by_default != null then
121
122 # Add `super Serializable`
123 var sc = toolcontext.parse_superclass("Serializable")
124 sc.location = nclassdef.location
125 nclassdef.n_propdefs.add sc
126
127 # Add services
128 var per_attribute = not serialize_by_default
129 generate_serialization_method(nclassdef, per_attribute)
130 generate_deserialization_init(nclassdef, per_attribute)
131 end
132 end
133
134 redef fun process_nmodule(nmodule)
135 do
136 # Clear the cache of constructors to review before adding to it
137 nmodule.inits_to_retype.clear
138
139 # collect all classes
140 var auto_serializable_nclassdefs = new Array[AStdClassdef]
141 for nclassdef in nmodule.n_classdefs do
142 if nclassdef isa AStdClassdef and nclassdef.how_serialize != null then
143 auto_serializable_nclassdefs.add nclassdef
144 end
145 end
146
147 if not auto_serializable_nclassdefs.is_empty then
148 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
149 end
150 end
151
152 fun generate_serialization_method(nclassdef: AClassdef, per_attribute: Bool)
153 do
154 var npropdefs = nclassdef.n_propdefs
155
156 var code = new Array[String]
157 code.add "redef fun core_serialize_to(v)"
158 code.add "do"
159 code.add " super"
160
161 for attribute in npropdefs do if attribute isa AAttrPropdef then
162
163 # Is `attribute` to be skipped?
164 if (per_attribute and not attribute.is_serialize) or
165 attribute.is_noserialize then continue
166
167 var name = attribute.name
168 code.add " v.serialize_attribute(\"{name}\", {name})"
169 end
170
171 code.add "end"
172
173 # Create method Node and add it to the AST
174 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
175 end
176
177 # Add a constructor to the automated nclassdef
178 fun generate_deserialization_init(nclassdef: AClassdef, per_attribute: Bool)
179 do
180 var npropdefs = nclassdef.n_propdefs
181
182 # Do not insert a `from_deserializer` if it already exists
183 for npropdef in npropdefs do
184 if npropdef isa AMethPropdef then
185 var methid = npropdef.n_methid
186 if methid != null and methid.collect_text == "from_deserializer" then
187 return
188 end
189 end
190 end
191
192 var code = new Array[String]
193 code.add """
194 redef init from_deserializer(v: Deserializer)
195 do
196 super
197 v.notify_of_creation self
198 """
199
200 for attribute in npropdefs do if attribute isa AAttrPropdef then
201
202 # Is `attribute` to be skipped?
203 if (per_attribute and not attribute.is_serialize) or
204 attribute.is_noserialize then continue
205
206 var n_type = attribute.n_type
207 var type_name
208 if n_type == null then
209 # Use a place holder, we will replace it with the inferred type after the model phases
210 type_name = toolcontext.place_holder_type_name
211 else
212 type_name = n_type.type_name
213 end
214 var name = attribute.name
215
216 code.add """
217 var {{{name}}} = v.deserialize_attribute("{{{name}}}")
218 if not {{{name}}} isa {{{type_name}}} then
219 # Check if it was a subjectent error
220 v.errors.add new AttributeTypeError("TODO remove this arg on c_src regen",
221 self, "{{{name}}}", {{{name}}}, "{{{type_name}}}")
222
223 # Clear subjacent error
224 if v.keep_going == false then return
225 else
226 self.{{{name}}} = {{{name}}}
227 end
228 """
229 end
230
231 code.add "end"
232
233 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
234 npropdefs.add npropdef
235 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
236 end
237
238 # Added to the abstract serialization service
239 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
240 do
241 var code = new Array[String]
242
243 var deserializer_nclassdef = nmodule.deserializer_nclassdef
244 var deserializer_npropdef
245 if deserializer_nclassdef == null then
246 # create the class
247 code.add "redef class Deserializer"
248 deserializer_npropdef = null
249 else
250 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
251 end
252
253 if deserializer_npropdef == null then
254 # create the property
255 code.add " redef fun deserialize_class_intern(name)"
256 code.add " do"
257 else
258 toolcontext.error(deserializer_npropdef.location, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
259 return
260 end
261
262 for nclassdef in nclassdefs do
263 var name = nclassdef.n_qid.n_id.text
264 if nclassdef.n_formaldefs.is_empty and
265 nclassdef.n_classkind isa AConcreteClasskind then
266
267 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
268 end
269 end
270
271 code.add " return super"
272 code.add " end"
273
274 if deserializer_nclassdef == null then
275 code.add "end"
276 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
277 else
278 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
279 end
280 end
281 end
282
283 private class SerializationPhasePostModel
284 super Phase
285
286 redef fun process_nmodule(nmodule)
287 do
288 for npropdef in nmodule.inits_to_retype do
289 var mpropdef = npropdef.mpropdef
290 if mpropdef == null then continue # skip error
291 var v = new PreciseTypeVisitor(npropdef, mpropdef.mclassdef, toolcontext)
292 npropdef.accept_precise_type_visitor v
293 end
294 end
295 end
296
297 # Visitor on generated constructors to replace the expected type of deserialized attributes
298 private class PreciseTypeVisitor
299 super Visitor
300
301 var npropdef: AMethPropdef
302 var mclassdef: MClassDef
303 var toolcontext: ToolContext
304
305 redef fun visit(n) do n.accept_precise_type_visitor(self)
306 end
307
308 redef class AIsaExpr
309 redef fun accept_precise_type_visitor(v)
310 do
311 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
312
313 var attr_name = "_" + n_expr.collect_text
314 for mattrdef in v.mclassdef.mpropdefs do
315 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
316 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
317 n_type.replace_with new_ntype
318 break
319 end
320 end
321 end
322 end
323
324 redef class AAttrPropdef
325 private fun name: String
326 do
327 return n_id2.text
328 end
329 end
330
331 redef class AType
332 private fun type_name: String
333 do
334 var name = n_qid.n_id.text
335
336 if n_kwnullable != null then name = "nullable {name}"
337
338 var types = n_types
339 if not types.is_empty then
340 var params = new Array[String]
341 for t in types do params.add(t.type_name)
342 return "{name}[{params.join(", ")}]"
343 else return name
344 end
345 end
346
347 redef class AModule
348 private fun deserializer_nclassdef: nullable AStdClassdef
349 do
350 for nclassdef in n_classdefs do
351 if nclassdef isa AStdClassdef and nclassdef.n_qid.n_id.text == "Deserializer" then
352 return nclassdef
353 end
354 end
355
356 return null
357 end
358
359 private var inits_to_retype = new Array[AMethPropdef]
360
361 redef fun is_serialize do return n_moduledecl != null and n_moduledecl.is_serialize
362 end
363
364 redef class AStdClassdef
365 private fun deserializer_npropdef: nullable AMethPropdef
366 do
367 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
368 var id = npropdef.n_methid
369 if id isa AIdMethid and id.n_id.text == "deserialize_class_intern" then
370 return npropdef
371 end
372 end
373
374 return null
375 end
376
377 # Is this classed marked `serialize`? in part or fully?
378 #
379 # This method returns 3 possible values:
380 # * `null`, this class is not to be serialized.
381 # * `true`, the attributes of this class are to be serialized by default.
382 # * `false`, the attributes of this class are to be serialized on demand only.
383 fun how_serialize: nullable Bool
384 do
385 # Is there a declaration on the classdef or the module?
386 var serialize = is_serialize
387
388 if not serialize and not is_noserialize then
389 # Is the module marked serialize?
390 serialize = parent.as(AModule).is_serialize
391 end
392
393 if serialize then return true
394
395 if not serialize then
396 # Is there an attribute marked serialize?
397 for npropdef in n_propdefs do
398 if npropdef.is_serialize then
399 return false
400 end
401 end
402 end
403
404 return null
405 end
406 end