nitc: update code to use qclassids
[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 var code = new Array[String]
183 code.add """
184 redef init from_deserializer(v: Deserializer)
185 do
186 super
187 v.notify_of_creation self
188 """
189
190 for attribute in npropdefs do if attribute isa AAttrPropdef then
191
192 # Is `attribute` to be skipped?
193 if (per_attribute and not attribute.is_serialize) or
194 attribute.is_noserialize then continue
195
196 var n_type = attribute.n_type
197 var type_name
198 if n_type == null then
199 # Use a place holder, we will replace it with the inferred type after the model phases
200 type_name = toolcontext.place_holder_type_name
201 else
202 type_name = n_type.type_name
203 end
204 var name = attribute.name
205
206 code.add """
207 var {{{name}}} = v.deserialize_attribute("{{{name}}}")
208 if not {{{name}}} isa {{{type_name}}} then
209 # Check if it was a subjectent error
210 v.errors.add new AttributeTypeError("TODO remove this arg on c_src regen",
211 self, "{{{name}}}", {{{name}}}, "{{{type_name}}}")
212
213 # Clear subjacent error
214 if v.keep_going == false then return
215 else
216 self.{{{name}}} = {{{name}}}
217 end
218 """
219 end
220
221 code.add "end"
222
223 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
224 npropdefs.add npropdef
225 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
226 end
227
228 # Added to the abstract serialization service
229 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
230 do
231 var code = new Array[String]
232
233 var deserializer_nclassdef = nmodule.deserializer_nclassdef
234 var deserializer_npropdef
235 if deserializer_nclassdef == null then
236 # create the class
237 code.add "redef class Deserializer"
238 deserializer_npropdef = null
239 else
240 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
241 end
242
243 if deserializer_npropdef == null then
244 # create the property
245 code.add " redef fun deserialize_class_intern(name)"
246 code.add " do"
247 else
248 toolcontext.error(deserializer_npropdef.location, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
249 return
250 end
251
252 for nclassdef in nclassdefs do
253 var name = nclassdef.n_qid.n_id.text
254 if nclassdef.n_formaldefs.is_empty and
255 nclassdef.n_classkind isa AConcreteClasskind then
256
257 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
258 end
259 end
260
261 code.add " return super"
262 code.add " end"
263
264 if deserializer_nclassdef == null then
265 code.add "end"
266 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
267 else
268 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
269 end
270 end
271 end
272
273 private class SerializationPhasePostModel
274 super Phase
275
276 redef fun process_nmodule(nmodule)
277 do
278 for npropdef in nmodule.inits_to_retype do
279 var mpropdef = npropdef.mpropdef
280 if mpropdef == null then continue # skip error
281 var v = new PreciseTypeVisitor(npropdef, mpropdef.mclassdef, toolcontext)
282 npropdef.accept_precise_type_visitor v
283 end
284 end
285 end
286
287 # Visitor on generated constructors to replace the expected type of deserialized attributes
288 private class PreciseTypeVisitor
289 super Visitor
290
291 var npropdef: AMethPropdef
292 var mclassdef: MClassDef
293 var toolcontext: ToolContext
294
295 redef fun visit(n) do n.accept_precise_type_visitor(self)
296 end
297
298 redef class AIsaExpr
299 redef fun accept_precise_type_visitor(v)
300 do
301 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
302
303 var attr_name = "_" + n_expr.collect_text
304 for mattrdef in v.mclassdef.mpropdefs do
305 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
306 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
307 n_type.replace_with new_ntype
308 break
309 end
310 end
311 end
312 end
313
314 redef class AAttrPropdef
315 private fun name: String
316 do
317 return n_id2.text
318 end
319 end
320
321 redef class AType
322 private fun type_name: String
323 do
324 var name = n_qid.n_id.text
325
326 if n_kwnullable != null then name = "nullable {name}"
327
328 var types = n_types
329 if not types.is_empty then
330 var params = new Array[String]
331 for t in types do params.add(t.type_name)
332 return "{name}[{params.join(", ")}]"
333 else return name
334 end
335 end
336
337 redef class AModule
338 private fun deserializer_nclassdef: nullable AStdClassdef
339 do
340 for nclassdef in n_classdefs do
341 if nclassdef isa AStdClassdef and nclassdef.n_qid.n_id.text == "Deserializer" then
342 return nclassdef
343 end
344 end
345
346 return null
347 end
348
349 private var inits_to_retype = new Array[AMethPropdef]
350
351 redef fun is_serialize do return n_moduledecl != null and n_moduledecl.is_serialize
352 end
353
354 redef class AStdClassdef
355 private fun deserializer_npropdef: nullable AMethPropdef
356 do
357 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
358 var id = npropdef.n_methid
359 if id isa AIdMethid and id.n_id.text == "deserialize_class_intern" then
360 return npropdef
361 end
362 end
363
364 return null
365 end
366
367 # Is this classed marked `serialize`? in part or fully?
368 #
369 # This method returns 3 possible values:
370 # * `null`, this class is not to be serialized.
371 # * `true`, the attributes of this class are to be serialized by default.
372 # * `false`, the attributes of this class are to be serialized on demand only.
373 fun how_serialize: nullable Bool
374 do
375 # Is there a declaration on the classdef or the module?
376 var serialize = is_serialize
377
378 if not serialize and not is_noserialize then
379 # Is the module marked serialize?
380 serialize = parent.as(AModule).is_serialize
381 end
382
383 if serialize then return true
384
385 if not serialize then
386 # Is there an attribute marked serialize?
387 for npropdef in n_propdefs do
388 if npropdef.is_serialize then
389 return false
390 end
391 end
392 end
393
394 return null
395 end
396 end