4ad749ba8f419524a742bcccb3a7eda0ca872056
[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 intrude import literal
26
27 redef class ToolContext
28
29 # Apply the annotation `serialize_as`
30 var serialization_phase_rename: Phase = new SerializationPhaseRename(self, null)
31
32 # Generate serialization and deserialization methods on `auto_serializable` annotated classes.
33 var serialization_phase_pre_model: Phase = new SerializationPhasePreModel(self,
34 [serialization_phase_rename])
35
36 # The second phase of the serialization
37 var serialization_phase_post_model: Phase = new SerializationPhasePostModel(self,
38 [modelize_property_phase, serialization_phase_pre_model])
39 end
40
41 redef class ANode
42 # Is this node annotated to be made serializable?
43 private fun is_serialize: Bool do return false
44
45 # Is this node annotated to not be made serializable?
46 private fun is_noserialize: Bool do return false
47 end
48
49 redef class ADefinition
50
51 redef fun is_serialize do
52 return get_annotations("serialize").not_empty or
53 get_annotations("auto_serializable").not_empty
54 end
55
56 redef fun is_noserialize do
57 return get_annotations("noserialize").not_empty
58 end
59 end
60
61 private class SerializationPhaseRename
62 super Phase
63
64 redef fun process_annotated_node(node, nat)
65 do
66 var text = nat.n_atid.n_id.text
67 if text != "serialize_as" then return
68
69 if not node isa AAttrPropdef then
70 toolcontext.error(node.location,
71 "Syntax Error: annotation `{text}` applies only to attributes.")
72 return
73 end
74
75 # Can't use `arg_as_string` because it needs the literal phase
76 var args = nat.n_args
77 if args.length != 1 or not args.first isa AStringFormExpr then
78 toolcontext.error(node.location,
79 "Syntax Error: annotation `{text}` expects a single string literal as argument.")
80 return
81 end
82
83 var t = args.first.collect_text
84 var val = t.substring(1, t.length-2)
85 node.serialize_name = val
86 end
87 end
88
89 private class SerializationPhasePreModel
90 super Phase
91
92 redef fun process_annotated_node(node, nat)
93 do
94 # Skip if we are not interested
95 var text = nat.n_atid.n_id.text
96 var serialize = text == "auto_serializable" or text == "serialize"
97 var noserialize = text == "noserialize"
98 if not (serialize or noserialize) then return
99
100 # Check legality of annotation
101 if node isa AModuledecl then
102 if noserialize then toolcontext.error(node.location, "Syntax Error: superfluous use of `{text}`, by default a module is `{text}`")
103 return
104 else if not (node isa AStdClassdef or node isa AAttrPropdef) then
105 toolcontext.error(node.location,
106 "Syntax Error: only a class, a module or an attribute can be annotated with `{text}`.")
107 return
108 else if serialize and node.is_noserialize then
109 toolcontext.error(node.location,
110 "Syntax Error: an entity cannot be both `{text}` and `noserialize`.")
111 return
112 else if node.as(Prod).get_annotations(text).length > 1 then
113 toolcontext.warning(node.location, "useless-{text}",
114 "Warning: duplicated annotation `{text}`.")
115 end
116
117 # Check the `serialize` state of the parent
118 if not node isa AModuledecl then
119 var up_serialize = false
120 var up: nullable ANode = node
121 while up != null do
122 up = up.parent
123 if up == null then
124 break
125 else if up.is_serialize then
126 up_serialize = true
127 break
128 else if up.is_noserialize then
129 break
130 end
131 end
132
133 # Check for useless double declarations
134 if serialize and up_serialize then
135 toolcontext.warning(node.location, "useless-serialize",
136 "Warning: superfluous use of `{text}`.")
137 else if noserialize and not up_serialize then
138 toolcontext.warning(node.location, "useless-noserialize",
139 "Warning: superfluous use of `{text}`.")
140 end
141 end
142 end
143
144 redef fun process_nclassdef(nclassdef)
145 do
146 if not nclassdef isa AStdClassdef then return
147
148 var serialize_by_default = nclassdef.how_serialize
149
150 if serialize_by_default != null then
151
152 # Add `super Serializable`
153 var sc = toolcontext.parse_superclass("Serializable")
154 sc.location = nclassdef.location
155 nclassdef.n_propdefs.add sc
156
157 # Add services
158 var per_attribute = not serialize_by_default
159 generate_serialization_method(nclassdef, per_attribute)
160 generate_deserialization_init(nclassdef)
161 end
162 end
163
164 redef fun process_nmodule(nmodule)
165 do
166 # Clear the cache of constructors to review before adding to it
167 nmodule.inits_to_retype.clear
168
169 # collect all classes
170 var auto_serializable_nclassdefs = nmodule.auto_serializable_nclassdefs
171 if not auto_serializable_nclassdefs.is_empty then
172 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
173 end
174 end
175
176 fun generate_serialization_method(nclassdef: AClassdef, per_attribute: Bool)
177 do
178 var npropdefs = nclassdef.n_propdefs
179
180 var code = new Array[String]
181 code.add "redef fun core_serialize_to(v)"
182 code.add "do"
183 code.add " super"
184
185 for attribute in npropdefs do if attribute isa AAttrPropdef then
186
187 # Is `attribute` to be skipped?
188 if (per_attribute and not attribute.is_serialize) or
189 attribute.is_noserialize then continue
190
191 code.add " v.serialize_attribute(\"{attribute.serialize_name}\", {attribute.name})"
192 end
193
194 code.add "end"
195
196 # Create method Node and add it to the AST
197 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
198 end
199
200 # Add an empty constructor to the automated nclassdef
201 #
202 # Will be filled by `SerializationPhasePostModel`.
203 fun generate_deserialization_init(nclassdef: AClassdef)
204 do
205 var npropdefs = nclassdef.n_propdefs
206
207 # Do not insert a `from_deserializer` if it already exists
208 for npropdef in npropdefs do
209 if npropdef isa AMethPropdef then
210 var methid = npropdef.n_methid
211 if methid != null and methid.collect_text == "from_deserializer" then
212 return
213 end
214 end
215 end
216
217 var code = """
218 redef init from_deserializer(v: Deserializer) do abort"""
219
220 var npropdef = toolcontext.parse_propdef(code).as(AMethPropdef)
221 npropdefs.add npropdef
222 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
223 end
224
225 # Add an empty `Deserializer::deserialize_class_intern`
226 #
227 # Will be filled by `SerializationPhasePostModel`.
228 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
229 do
230 var code = new Array[String]
231
232 var deserializer_nclassdef = nmodule.deserializer_nclassdef
233 var deserializer_npropdef
234 if deserializer_nclassdef == null then
235 # create the class
236 code.add "redef class Deserializer"
237 deserializer_npropdef = null
238 else
239 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
240 end
241
242 if deserializer_npropdef == null then
243 # create the property
244 code.add " redef fun deserialize_class_intern(name) do abort"
245 else
246 toolcontext.error(deserializer_npropdef.location, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
247 return
248 end
249
250 if deserializer_nclassdef == null then
251 code.add "end"
252 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
253 else
254 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
255 end
256 end
257 end
258
259 private class SerializationPhasePostModel
260 super Phase
261
262 redef fun process_nmodule(nmodule)
263 do
264 for npropdef in nmodule.inits_to_retype do
265 var nclassdef = npropdef.parent
266 assert nclassdef isa AStdClassdef
267
268 var serialize_by_default = nclassdef.how_serialize
269 assert serialize_by_default != null
270
271 var per_attribute = not serialize_by_default
272 fill_deserialization_init(nclassdef, npropdef, per_attribute)
273 end
274
275 # collect all classes
276 var auto_serializable_nclassdefs = nmodule.auto_serializable_nclassdefs
277 if not auto_serializable_nclassdefs.is_empty then
278 fill_deserialization_method(nmodule, auto_serializable_nclassdefs)
279 end
280 end
281
282 # Fill the constructor to the generated `init_npropdef` of `nclassdef`
283 fun fill_deserialization_init(nclassdef: AClassdef, init_npropdef: AMethPropdef, per_attribute: Bool)
284 do
285 var code = new Array[String]
286 code.add """
287 redef init from_deserializer(v: Deserializer)
288 do
289 super
290 v.notify_of_creation self
291 """
292
293 for attribute in nclassdef.n_propdefs do
294 if not attribute isa AAttrPropdef then continue
295
296 # Is `attribute` to be skipped?
297 if (per_attribute and not attribute.is_serialize) or
298 attribute.is_noserialize then continue
299
300 var mtype = attribute.mtype
301 if mtype == null then continue
302 var type_name = mtype.to_s
303 var name = attribute.name
304
305 if type_name == "nullable Object" then
306 # Don't type check
307 code.add """
308 var {{{name}}} = v.deserialize_attribute("{{{attribute.serialize_name}}}", "{{{type_name}}}")
309 """
310 else code.add """
311 var {{{name}}} = v.deserialize_attribute("{{{attribute.serialize_name}}}", "{{{type_name}}}")
312 if not {{{name}}} isa {{{type_name}}} then
313 # Check if it was a subjectent error
314 v.errors.add new AttributeTypeError(self, "{{{attribute.serialize_name}}}", {{{name}}}, "{{{type_name}}}")
315
316 # Clear subjacent error
317 if v.keep_going == false then return
318 else
319 self.{{{name}}} = {{{name}}}
320 end
321 """
322 end
323
324 code.add "end"
325
326 # Replace the body of the constructor
327 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
328 init_npropdef.n_block = npropdef.n_block
329
330 # Run the literal phase on the generated code
331 var v = new LiteralVisitor(toolcontext)
332 v.enter_visit(npropdef.n_block)
333 end
334
335 # Fill the abstract serialization service
336 fun fill_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
337 do
338 var deserializer_nclassdef = nmodule.deserializer_nclassdef
339 if deserializer_nclassdef == null then return
340 var deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
341 if deserializer_npropdef == null then return
342
343 # Collect local types expected to be deserialized
344 var types_to_deserialize = new Set[String]
345
346 ## Local serializable standard class without parameters
347 for nclassdef in nclassdefs do
348 var mclass = nclassdef.mclass
349 if mclass == null then continue
350
351 if mclass.arity == 0 and mclass.kind == concrete_kind then
352 types_to_deserialize.add mclass.name
353 end
354 end
355
356 ## Static parametized types on serializable attributes
357 for nclassdef in nmodule.n_classdefs do
358 if not nclassdef isa AStdClassdef then continue
359
360 for attribute in nclassdef.n_propdefs do
361 if not attribute isa AAttrPropdef then continue
362
363 var serialize_by_default = nclassdef.how_serialize
364 if serialize_by_default == null then continue
365 var per_attribute = not serialize_by_default
366
367 # Is `attribute` to be skipped?
368 if (per_attribute and not attribute.is_serialize) or
369 attribute.is_noserialize then continue
370
371 var mtype = attribute.mtype
372 if mtype == null then continue
373 if mtype isa MNullableType then mtype = mtype.mtype
374
375 if mtype isa MClassType and mtype.mclass.arity > 0 and
376 mtype.mclass.kind == concrete_kind and not mtype.need_anchor then
377
378 # Check is a `Serializable`
379 var mmodule = nmodule.mmodule
380 if mmodule == null then continue
381
382 var greaters = mtype.mclass.in_hierarchy(mmodule).greaters
383 var is_serializable = false
384 for sup in greaters do if sup.name == "Serializable" then
385 is_serializable = true
386 break
387 end
388
389 if is_serializable then types_to_deserialize.add mtype.to_s
390 end
391 end
392 end
393
394 # Build implementation code
395 var code = new Array[String]
396 code.add "redef fun deserialize_class_intern(name)"
397 code.add "do"
398
399 for name in types_to_deserialize do
400 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
401 end
402
403 code.add " return super"
404 code.add "end"
405
406 # Replace the body of the constructor
407 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
408 deserializer_npropdef.n_block = npropdef.n_block
409
410 # Run the literal phase on the generated code
411 var v = new LiteralVisitor(toolcontext)
412 v.enter_visit(npropdef.n_block)
413 end
414 end
415
416 redef class AAttrPropdef
417 private fun name: String do return n_id2.text
418
419 # Name of this attribute in the serialized format
420 private var serialize_name: String = name is lazy
421 end
422
423 redef class AType
424 private fun type_name: String
425 do
426 var name = n_qid.n_id.text
427
428 if n_kwnullable != null then name = "nullable {name}"
429
430 var types = n_types
431 if not types.is_empty then
432 var params = new Array[String]
433 for t in types do params.add(t.type_name)
434 return "{name}[{params.join(", ")}]"
435 else return name
436 end
437 end
438
439 redef class AModule
440 private fun deserializer_nclassdef: nullable AStdClassdef
441 do
442 for nclassdef in n_classdefs do
443 if not nclassdef isa AStdClassdef then continue
444 var n_qid = nclassdef.n_qid
445 if n_qid != null and n_qid.n_id.text == "Deserializer" then return nclassdef
446 end
447
448 return null
449 end
450
451 private var inits_to_retype = new Array[AMethPropdef]
452
453 redef fun is_serialize
454 do
455 var n_moduledecl = n_moduledecl
456 return n_moduledecl != null and n_moduledecl.is_serialize
457 end
458
459 # `AStdClassdef` marked as serializable, itself or one of theur attribute
460 private var auto_serializable_nclassdefs: Array[AStdClassdef] is lazy do
461 var array = new Array[AStdClassdef]
462 for nclassdef in n_classdefs do
463 if nclassdef isa AStdClassdef and nclassdef.how_serialize != null then
464 array.add nclassdef
465 end
466 end
467 return array
468 end
469 end
470
471 redef class AStdClassdef
472 private fun deserializer_npropdef: nullable AMethPropdef
473 do
474 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
475 var id = npropdef.n_methid
476 if id isa AIdMethid and id.n_id.text == "deserialize_class_intern" then
477 return npropdef
478 end
479 end
480
481 return null
482 end
483
484 # Is this classed marked `serialize`? in part or fully?
485 #
486 # This method returns 3 possible values:
487 # * `null`, this class is not to be serialized.
488 # * `true`, the attributes of this class are to be serialized by default.
489 # * `false`, the attributes of this class are to be serialized on demand only.
490 fun how_serialize: nullable Bool
491 do
492 # Is there a declaration on the classdef or the module?
493 var serialize = is_serialize
494
495 if not serialize and not is_noserialize then
496 # Is the module marked serialize?
497 serialize = parent.as(AModule).is_serialize
498 end
499
500 if serialize then return true
501
502 if not serialize then
503 # Is there an attribute marked serialize?
504 for npropdef in n_propdefs do
505 if npropdef.is_serialize then
506 return false
507 end
508 end
509 end
510
511 return null
512 end
513 end