ec472c2b05c015d1cb4d60bed49570100e5d2478
[nit.git] / src / 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 import phase
23 import parser_util
24 import modelize_property
25 intrude import modelize_class
26
27 redef class ToolContext
28 var serialization_phase_pre_model: Phase = new SerializationPhasePreModel(self, null)
29 var serialization_phase_post_model: Phase = new SerializationPhasePostModel(self,
30 [modelize_class_phase, serialization_phase_pre_model])
31
32 private fun place_holder_type_name: String do return "PlaceHolderTypeWhichShouldNotExist"
33 end
34
35 # TODO add annotations on attributes (volatile, sensitive or do_not_serialize?)
36 private class SerializationPhasePreModel
37 super Phase
38
39 redef fun process_annotated_node(nclassdef, nat)
40 do
41 # Skip if we are not interested
42 if nat.n_atid.n_id.text != "auto_serializable" then return
43 if not nclassdef isa AStdClassdef then
44 toolcontext.error(nclassdef.location, "Syntax error: only a concrete class can be automatically serialized.")
45 return
46 end
47
48 # Add `super Serializable`
49 var sc = toolcontext.parse_superclass("Serializable")
50 sc.location = nat.location
51 nclassdef.n_superclasses.add sc
52
53 generate_serialization_method(nclassdef)
54
55 generate_deserialization_init(nclassdef)
56 end
57
58 redef fun process_nmodule(nmodule)
59 do
60 # Clear the cache of constructors to review before adding to it
61 nmodule.inits_to_retype.clear
62
63 # collect all classes
64 var auto_serializable_nclassdefs = new Array[AStdClassdef]
65 for nclassdef in nmodule.n_classdefs do
66 if nclassdef isa AStdClassdef and
67 not nclassdef.get_annotations("auto_serializable").is_empty then
68 auto_serializable_nclassdefs.add nclassdef
69 end
70 end
71
72 if not auto_serializable_nclassdefs.is_empty then
73 generate_deserialization_method(nmodule, auto_serializable_nclassdefs)
74 end
75 end
76
77 private fun generate_serialization_method(nclassdef: AClassdef)
78 do
79 var npropdefs = nclassdef.n_propdefs
80
81 var code = new Array[String]
82 code.add "redef fun core_serialize_to(v)"
83 code.add "do"
84 code.add " super"
85
86 for attribute in npropdefs do if attribute isa AAttrPropdef then
87 var name = attribute.name
88 code.add " v.serialize_attribute(\"{name}\", {name})"
89 end
90
91 code.add "end"
92
93 # Create method Node and add it to the AST
94 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
95 end
96
97 # Add a constructor to the automated nclassdef
98 private fun generate_deserialization_init(nclassdef: AClassdef)
99 do
100 var npropdefs = nclassdef.n_propdefs
101
102 var code = new Array[String]
103 code.add "init from_deserializer(v: Deserializer)"
104 code.add "do"
105 code.add " v.notify_of_creation self"
106
107 for attribute in npropdefs do if attribute isa AAttrPropdef then
108 var n_type = attribute.n_type
109 var type_name
110 if n_type == null then
111 # Use a place holder, we will replace it with the infered type after the model phases
112 type_name = toolcontext.place_holder_type_name
113 else
114 type_name = n_type.type_name
115 end
116 var name = attribute.name
117
118 code.add ""
119 code.add "\tvar {name} = v.deserialize_attribute(\"{name}\")"
120 code.add "\tassert {name} isa {type_name} else print \"Unsupported type for attribute '{name}', got '\{{name}.class_name\}' (ex {type_name})\""
121 code.add "\tself.{name} = {name}"
122 end
123
124 code.add "end"
125
126 var npropdef = toolcontext.parse_propdef(code.join("\n")).as(AConcreteInitPropdef)
127 npropdefs.add npropdef
128 nclassdef.parent.as(AModule).inits_to_retype.add npropdef
129 end
130
131 # Added to the abstract serialization service
132 private fun generate_deserialization_method(nmodule: AModule, nclassdefs: Array[AStdClassdef])
133 do
134 var code = new Array[String]
135
136 var deserializer_nclassdef = nmodule.deserializer_nclassdef
137 var deserializer_npropdef
138 if deserializer_nclassdef == null then
139 # create the class
140 code.add "redef class Deserializer"
141 deserializer_npropdef = null
142 else
143 deserializer_npropdef = deserializer_nclassdef.deserializer_npropdef
144 end
145
146 if deserializer_npropdef == null then
147 # create the property
148 code.add " redef fun deserialize_class(name)"
149 code.add " do"
150 else
151 toolcontext.error(deserializer_npropdef.location, "Annotation error: you cannot define Deserializer::deserialize_class in a module where you use \"auto_serializable\".")
152 return
153 end
154
155 for nclassdef in nclassdefs do
156 var name = nclassdef.n_id.text
157 if nclassdef.n_formaldefs.is_empty then
158 code.add " if name == \"{name}\" then return new {name}.from_deserializer(self)"
159 end
160 end
161
162 code.add " return super"
163 code.add " end"
164
165 if deserializer_nclassdef == null then
166 code.add "end"
167 nmodule.n_classdefs.add toolcontext.parse_classdef(code.join("\n"))
168 else
169 deserializer_nclassdef.n_propdefs.add(toolcontext.parse_propdef(code.join("\n")))
170 end
171 end
172 end
173
174 private class SerializationPhasePostModel
175 super Phase
176
177 redef fun process_nmodule(nmodule)
178 do
179 for npropdef in nmodule.inits_to_retype do
180 var v = new PreciseTypeVisitor(npropdef, npropdef.mpropdef.mclassdef, toolcontext)
181 npropdef.accept_precise_type_visitor v
182 end
183 end
184 end
185
186 # Visitor on generated constructors to replace the expected type of deserialized attributes
187 private class PreciseTypeVisitor
188 super Visitor
189
190 var npropdef: AConcreteInitPropdef
191 var mclassdef: MClassDef
192 var toolcontext: ToolContext
193
194 init(npropdef: AConcreteInitPropdef, mclassdef: MClassDef, toolcontext: ToolContext)
195 do
196 self.npropdef = npropdef
197 self.mclassdef = mclassdef
198 self.toolcontext = toolcontext
199 end
200
201 redef fun visit(n) do n.accept_precise_type_visitor(self)
202 end
203
204 redef class ANode
205 private fun accept_precise_type_visitor(v: PreciseTypeVisitor) do visit_all(v)
206 end
207
208 redef class AIsaExpr
209 redef fun accept_precise_type_visitor(v)
210 do
211 if n_type.collect_text != v.toolcontext.place_holder_type_name then return
212
213 var attr_name = "_" + n_expr.collect_text
214 for mattrdef in v.mclassdef.mpropdefs do
215 if mattrdef isa MAttributeDef and mattrdef.name == attr_name then
216 var new_ntype = v.toolcontext.parse_something(mattrdef.static_mtype.to_s)
217 n_type.replace_with new_ntype
218 break
219 end
220 end
221 end
222 end
223
224 redef class AAttrPropdef
225 private fun name: String
226 do
227 if n_id == null then return n_id2.text
228 return n_id.text
229 end
230 end
231
232 redef class AType
233 private fun type_name: String
234 do
235 var name = n_id.text
236
237 if n_kwnullable != null then name = "nullable {name}"
238
239 var types = n_types
240 if not types.is_empty then
241 var params = new Array[String]
242 for t in types do params.add(t.type_name)
243 return "{name}[{params.join(", ")}]"
244 else return name
245 end
246 end
247
248 redef class AModule
249 private fun deserializer_nclassdef: nullable AStdClassdef
250 do
251 for nclassdef in n_classdefs do
252 if nclassdef isa AStdClassdef and nclassdef.n_id.text == "Deserialization" then
253 return nclassdef
254 end
255 end
256
257 return null
258 end
259
260 private var inits_to_retype = new Array[AConcreteInitPropdef]
261 end
262
263 redef class AStdClassdef
264 private fun deserializer_npropdef: nullable AMethPropdef
265 do
266 for npropdef in n_propdefs do if npropdef isa AMethPropdef then
267 var id = npropdef.n_methid
268 if id isa AIdMethid and id.n_id.text == "deserialize_class" then
269 return npropdef
270 end
271 end
272
273 return null
274 end
275 end