src/serialization: move adding the `Serializable` super class at the nclassdef
[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
89 generate_serialization_method(nclassdef)
90 end
91
92 generate_deserialization_init(nclassdef)
93 redef fun process_nclassdef(nclassdef)
94 do
95 # Add `super Serializable`
96 var sc = toolcontext.parse_superclass("Serializable")
97 sc.location = nclassdef.location
98 nclassdef.n_propdefs.add sc
99 end
100
101 redef fun process_nmodule(nmodule)
102 do
103 # Clear the cache of constructors to review before adding to it
104 nmodule.inits_to_retype.clear
105
106 # collect all classes
107 var auto_serializable_nclassdefs = new Array[AStdClassdef]
108 for nclassdef in nmodule.n_classdefs do
109 if nclassdef isa AStdClassdef and nclassdef.is_serialize then
110 auto_serializable_nclassdefs.add nclassdef
111 end
112 end
113
114 if not auto_serializable_nclassdefs.is_empty then
115 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
116 end
117 end
118
119 fun generate_serialization_method(nclassdef: AClassdef)
120 do
121 var npropdefs = nclassdef.n_propdefs
122
123 var code = new Array[String]
124 code.add "redef fun core_serialize_to(v)"
125 code.add "do"
126 code.add " super"
127
128 for attribute in npropdefs do if attribute isa AAttrPropdef then
129 var name = attribute.name
130 code.add " v.serialize_attribute(\"{name}\", {name})"
131 end
132
133 code.add "end"
134
135 # Create method Node and add it to the AST
136 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
137 end
138
139 # Add a constructor to the automated nclassdef
140 fun generate_deserialization_init(nclassdef: AStdClassdef)
141 do
142 var npropdefs = nclassdef.n_propdefs
143
144 var code = new Array[String]
145 code.add "redef init from_deserializer(v: Deserializer)"
146 code.add "do"
147 code.add " super"
148 code.add " v.notify_of_creation self"
149
150 for attribute in npropdefs do if attribute isa AAttrPropdef then
151 var n_type = attribute.n_type
152 var type_name
153 if n_type == null then
154 # Use a place holder, we will replace it with the infered type after the model phases
155 type_name = toolcontext.place_holder_type_name
156 else
157 type_name = n_type.type_name
158 end
159 var name = attribute.name
160
161 code.add ""
162 code.add "\tvar {name} = v.deserialize_attribute(\"{name}\")"
163 code.add "\tassert {name} isa {type_name} else print \"Unsupported type for `\{class_name\}::{name}`, got '\{{name}.class_name\}'; expected {type_name}\""
164 code.add "\tself.{name} = {name}"
165 end
166
167 code.add "end"
168
169 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AMethPropdef)
170 npropdefs.add npropdef
171 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
172 end
173
174 # Added to the abstract serialization service
175 fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
176 do
177 var code = new Array[String]
178
179 var deserializer_nclassdef = nmodule.deserializer_nclassdef
180 var deserializer_npropdef
181 if deserializer_nclassdef == null then
182 # create the class
183 code.add "redef class Deserializer"
184 deserializer_npropdef = null
185 else
186 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
187 end
188
189 if deserializer_npropdef == null then
190 # create the property
191 code.add " redef fun deserialize_class(name)"
192 code.add " do"
193 else
194 toolcontext.error(deserializer_npropdef.location, "Error: you cannot define `Deserializer::deserialize_class` in a module where you use `auto_serializable`.")
195 return
196 end
197
198 for nclassdef in nclassdefs do
199 var name = nclassdef.n_id.text
200 if nclassdef.n_formaldefs.is_empty and
201 not nclassdef.n_classkind isa AAbstractClasskind then
202
203 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
204 end
205 end
206
207 code.add " return super"
208 code.add " end"
209
210 if deserializer_nclassdef == null then
211 code.add "end"
212 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
213 else
214 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
215 end
216 end
217 end
218
219 private class SerializationPhasePostModel
220 super Phase
221
222 redef fun process_nmodule(nmodule)
223 do
224 for npropdef in nmodule.inits_to_retype do
225 var mpropdef = npropdef.mpropdef
226 if mpropdef == null then continue # skip error
227 var v = new PreciseTypeVisitor(npropdef, mpropdef.mclassdef, toolcontext)
228 npropdef.accept_precise_type_visitor v
229 end
230 end
231 end
232
233 # Visitor on generated constructors to replace the expected type of deserialized attributes
234 private class PreciseTypeVisitor
235 super Visitor
236
237 var npropdef: AMethPropdef
238 var mclassdef: MClassDef
239 var toolcontext: ToolContext
240
241 redef fun visit(n) do n.accept_precise_type_visitor(self)
242 end
243
244 redef class AIsaExpr
245 redef fun accept_precise_type_visitor(v)
246 do
247 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
248
249 var attr_name = "_" + n_expr.collect_text
250 for mattrdef in v.mclassdef.mpropdefs do
251 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
252 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
253 n_type.replace_with new_ntype
254 break
255 end
256 end
257 end
258 end
259
260 redef class AAttrPropdef
261 private fun name: String
262 do
263 return n_id2.text
264 end
265 end
266
267 redef class AType
268 private fun type_name: String
269 do
270 var name = n_id.text
271
272 if n_kwnullable != null then name = "nullable {name}"
273
274 var types = n_types
275 if not types.is_empty then
276 var params = new Array[String]
277 for t in types do params.add(t.type_name)
278 return "{name}[{params.join(", ")}]"
279 else return name
280 end
281 end
282
283 redef class AModule
284 private fun deserializer_nclassdef: nullable AStdClassdef
285 do
286 for nclassdef in n_classdefs do
287 if nclassdef isa AStdClassdef and nclassdef.n_id.text == "Deserialization" then
288 return nclassdef
289 end
290 end
291
292 return null
293 end
294
295 private var inits_to_retype = new Array[AMethPropdef]
296 end
297
298 redef class AStdClassdef
299 private fun deserializer_npropdef: nullable AMethPropdef
300 do
301 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
302 var id = npropdef.n_methid
303 if id isa AIdMethid and id.n_id.text == "deserialize_class" then
304 return npropdef
305 end
306 end
307
308 return null
309 end
310 end