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