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