Merge: Deserialization manage errors & easily create Nit object from pure JSON
[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 # Is there a declaration on the classdef or the module?
120 var serialize = nclassdef.is_serialize
121
122 if not serialize and not nclassdef.is_noserialize then
123 # Is the module marked serialize?
124 serialize = nclassdef.parent.as(AModule).is_serialize
125 end
126
127 var per_attribute = false
128 if not serialize then
129 # Is there an attribute marked serialize?
130 for npropdef in nclassdef.n_propdefs do
131 if npropdef.is_serialize then
132 serialize = true
133 per_attribute = true
134 break
135 end
136 end
137 end
138
139 if serialize then
140 # Add `super Serializable`
141 var sc = toolcontext.parse_superclass("Serializable")
142 sc.location = nclassdef.location
143 nclassdef.n_propdefs.add sc
144
145 # Add services
146 generate_serialization_method(nclassdef, per_attribute)
147 generate_deserialization_init(nclassdef, per_attribute)
148 end
149 end
150
151 redef fun process_nmodule(nmodule)
152 do
153 # Clear the cache of constructors to review before adding to it
154 nmodule.inits_to_retype.clear
155
156 # collect all classes
157 var auto_serializable_nclassdefs = new Array[AStdClassdef]
158 for nclassdef in nmodule.n_classdefs do
159 if nclassdef isa AStdClassdef and nclassdef.is_serialize then
160 auto_serializable_nclassdefs.add nclassdef
161 end
162 end
163
164 if not auto_serializable_nclassdefs.is_empty then
165 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
166 end
167 end
168
169 fun generate_serialization_method(nclassdef: AClassdef, per_attribute: Bool)
170 do
171 var npropdefs = nclassdef.n_propdefs
172
173 var code = new Array[String]
174 code.add "redef fun core_serialize_to(v)"
175 code.add "do"
176 code.add " super"
177
178 for attribute in npropdefs do if attribute isa AAttrPropdef then
179
180 # Is `attribute` to be skipped?
181 if (per_attribute and not attribute.is_serialize) or
182 attribute.is_noserialize then continue
183
184 var name = attribute.name
185 code.add " v.serialize_attribute(\"{name}\", {name})"
186 end
187
188 code.add "end"
189
190 # Create method Node and add it to the AST
191 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
192 end
193
194 # Add a constructor to the automated nclassdef
195 fun generate_deserialization_init(nclassdef: AClassdef, per_attribute: Bool)
196 do
197 var npropdefs = nclassdef.n_propdefs
198
199 var code = new Array[String]
200 code.add """
201 redef init from_deserializer(v: Deserializer)
202 do
203 super
204 v.notify_of_creation self
205 """
206
207 for attribute in npropdefs do if attribute isa AAttrPropdef then
208
209 # Is `attribute` to be skipped?
210 if (per_attribute and not attribute.is_serialize) or
211 attribute.is_noserialize then continue
212
213 var n_type = attribute.n_type
214 var type_name
215 if n_type == null then
216 # Use a place holder, we will replace it with the inferred type after the model phases
217 type_name = toolcontext.place_holder_type_name
218 else
219 type_name = n_type.type_name
220 end
221 var name = attribute.name
222
223 code.add """
224 var {{{name}}} = v.deserialize_attribute("{{{name}}}")
225 if not {{{name}}} isa {{{type_name}}} then
226 # Check if it was a subjectent error
227 v.errors.add new AttributeTypeError("TODO remove this arg on c_src regen",
228 self, "{{{name}}}", {{{name}}}, "{{{type_name}}}")
229
230 # Clear subjacent error
231 if v.keep_going == false then return
232 else
233 self.{{{name}}} = {{{name}}}
234 end
235 """
236 end
237
238 code.add "end"
239
240 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
241 npropdefs.add npropdef
242 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
243 end
244
245 # Added to the abstract serialization service
246 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
247 do
248 var code = new Array[String]
249
250 var deserializer_nclassdef = nmodule.deserializer_nclassdef
251 var deserializer_npropdef
252 if deserializer_nclassdef == null then
253 # create the class
254 code.add "redef class Deserializer"
255 deserializer_npropdef = null
256 else
257 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
258 end
259
260 if deserializer_npropdef == null then
261 # create the property
262 code.add " redef fun deserialize_class_intern(name)"
263 code.add " do"
264 else
265 toolcontext.error(deserializer_npropdef.location, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
266 return
267 end
268
269 for nclassdef in nclassdefs do
270 var name = nclassdef.n_id.text
271 if nclassdef.n_formaldefs.is_empty and
272 not nclassdef.n_classkind isa AAbstractClasskind then
273
274 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
275 end
276 end
277
278 code.add " return super"
279 code.add " end"
280
281 if deserializer_nclassdef == null then
282 code.add "end"
283 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
284 else
285 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
286 end
287 end
288 end
289
290 private class SerializationPhasePostModel
291 super Phase
292
293 redef fun process_nmodule(nmodule)
294 do
295 for npropdef in nmodule.inits_to_retype do
296 var mpropdef = npropdef.mpropdef
297 if mpropdef == null then continue # skip error
298 var v = new PreciseTypeVisitor(npropdef, mpropdef.mclassdef, toolcontext)
299 npropdef.accept_precise_type_visitor v
300 end
301 end
302 end
303
304 # Visitor on generated constructors to replace the expected type of deserialized attributes
305 private class PreciseTypeVisitor
306 super Visitor
307
308 var npropdef: AMethPropdef
309 var mclassdef: MClassDef
310 var toolcontext: ToolContext
311
312 redef fun visit(n) do n.accept_precise_type_visitor(self)
313 end
314
315 redef class AIsaExpr
316 redef fun accept_precise_type_visitor(v)
317 do
318 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
319
320 var attr_name = "_" + n_expr.collect_text
321 for mattrdef in v.mclassdef.mpropdefs do
322 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
323 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
324 n_type.replace_with new_ntype
325 break
326 end
327 end
328 end
329 end
330
331 redef class AAttrPropdef
332 private fun name: String
333 do
334 return n_id2.text
335 end
336 end
337
338 redef class AType
339 private fun type_name: String
340 do
341 var name = n_id.text
342
343 if n_kwnullable != null then name = "nullable {name}"
344
345 var types = n_types
346 if not types.is_empty then
347 var params = new Array[String]
348 for t in types do params.add(t.type_name)
349 return "{name}[{params.join(", ")}]"
350 else return name
351 end
352 end
353
354 redef class AModule
355 private fun deserializer_nclassdef: nullable AStdClassdef
356 do
357 for nclassdef in n_classdefs do
358 if nclassdef isa AStdClassdef and nclassdef.n_id.text == "Deserializer" then
359 return nclassdef
360 end
361 end
362
363 return null
364 end
365
366 private var inits_to_retype = new Array[AMethPropdef]
367
368 redef fun is_serialize do return n_moduledecl != null and n_moduledecl.is_serialize
369 end
370
371 redef class AStdClassdef
372 private fun deserializer_npropdef: nullable AMethPropdef
373 do
374 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
375 var id = npropdef.n_methid
376 if id isa AIdMethid and id.n_id.text == "deserialize_class_intern" then
377 return npropdef
378 end
379 end
380
381 return null
382 end
383 end