1 # This file is part of NIT ( http://www.nitlanguage.org ).
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>
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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.
19 # Phase generating methods to serialize Nit objects to different formats
20 module serialization_phase
22 private import parser_util
24 private import annotation
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)
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
])
34 private fun place_holder_type_name
: String do return "PlaceHolderTypeWhichShouldNotExist"
38 # Is this node annotated to be made serializable?
39 private fun is_serialize
: Bool do return false
41 # Is this node annotated to not be made serializable?
42 private fun is_noserialize
: Bool do return false
44 private fun accept_precise_type_visitor
(v
: PreciseTypeVisitor) do visit_all
(v
)
47 redef class ADefinition
49 redef fun is_serialize
do
50 return get_annotations
("serialize").not_empty
or
51 get_annotations
("auto_serializable").not_empty
54 redef fun is_noserialize
do
55 return get_annotations
("noserialize").not_empty
59 private class SerializationPhasePreModel
62 redef fun process_annotated_node
(node
, nat
)
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
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}`")
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}`.")
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`.")
82 else if node
.as(Prod).get_annotations
(text
).length
> 1 then
83 toolcontext
.warning
(node
.location
, "useless-{text}",
84 "Warning: duplicated annotation `{text}`.")
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
95 else if up
.is_serialize
then
98 else if up
.is_noserialize
then
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}`.")
114 redef fun process_nclassdef
(nclassdef
)
116 if not nclassdef
isa AStdClassdef then return
118 var serialize_by_default
= nclassdef
.how_serialize
120 if serialize_by_default
!= null then
122 # Add `super Serializable`
123 var sc
= toolcontext
.parse_superclass
("Serializable")
124 sc
.location
= nclassdef
.location
125 nclassdef
.n_propdefs
.add sc
128 var per_attribute
= not serialize_by_default
129 generate_serialization_method
(nclassdef
, per_attribute
)
130 generate_deserialization_init
(nclassdef
, per_attribute
)
134 redef fun process_nmodule
(nmodule
)
136 # Clear the cache of constructors to review before adding to it
137 nmodule
.inits_to_retype
.clear
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
147 if not auto_serializable_nclassdefs
.is_empty
then
148 generate_deserialization_method
(nmodule
, auto_serializable_nclassdefs
)
152 fun generate_serialization_method
(nclassdef
: AClassdef, per_attribute
: Bool)
154 var npropdefs
= nclassdef
.n_propdefs
156 var code
= new Array[String]
157 code
.add
"redef fun core_serialize_to(v)"
161 for attribute
in npropdefs
do if attribute
isa AAttrPropdef then
163 # Is `attribute` to be skipped?
164 if (per_attribute
and not attribute
.is_serialize
) or
165 attribute
.is_noserialize
then continue
167 var name
= attribute
.name
168 code
.add
" v.serialize_attribute(\"{name}\
", {name})"
173 # Create method Node and add it to the AST
174 npropdefs
.push
(toolcontext
.parse_propdef
(code
.join
("\n")))
177 # Add a constructor to the automated nclassdef
178 fun generate_deserialization_init
(nclassdef
: AClassdef, per_attribute
: Bool)
180 var npropdefs
= nclassdef
.n_propdefs
182 var code
= new Array[String]
184 redef init from_deserializer(v: Deserializer)
187 v.notify_of_creation self
190 for attribute
in npropdefs
do if attribute
isa AAttrPropdef then
192 # Is `attribute` to be skipped?
193 if (per_attribute
and not attribute
.is_serialize
) or
194 attribute
.is_noserialize
then continue
196 var n_type
= attribute
.n_type
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
202 type_name
= n_type
.type_name
204 var name
= attribute
.name
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}}}")
213 # Clear subjacent error
214 if v.keep_going == false then return
216 self.{{{name}}} = {{{name}}}
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
228 # Added to the abstract serialization service
229 fun generate_deserialization_method
(nmodule
: AModule, nclassdefs
: Array[AStdClassdef])
231 var code
= new Array[String]
233 var deserializer_nclassdef
= nmodule
.deserializer_nclassdef
234 var deserializer_npropdef
235 if deserializer_nclassdef
== null then
237 code
.add
"redef class Deserializer"
238 deserializer_npropdef
= null
240 deserializer_npropdef
= deserializer_nclassdef
.deserializer_npropdef
243 if deserializer_npropdef
== null then
244 # create the property
245 code
.add
" redef fun deserialize_class_intern(name)"
248 toolcontext
.error
(deserializer_npropdef
.location
, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
252 for nclassdef
in nclassdefs
do
253 var name
= nclassdef
.n_id
.text
254 if nclassdef
.n_formaldefs
.is_empty
and
255 nclassdef
.n_classkind
isa AConcreteClasskind then
257 code
.add
" if name == \"{name}\
" then return new {name}.from_deserializer(self)"
261 code
.add
" return super"
264 if deserializer_nclassdef
== null then
266 nmodule
.n_classdefs
.add toolcontext
.parse_classdef
(code
.join
("\n"))
268 deserializer_nclassdef
.n_propdefs
.add
(toolcontext
.parse_propdef
(code
.join
("\n")))
273 private class SerializationPhasePostModel
276 redef fun process_nmodule
(nmodule
)
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
287 # Visitor on generated constructors to replace the expected type of deserialized attributes
288 private class PreciseTypeVisitor
291 var npropdef
: AMethPropdef
292 var mclassdef
: MClassDef
293 var toolcontext
: ToolContext
295 redef fun visit
(n
) do n
.accept_precise_type_visitor
(self)
299 redef fun accept_precise_type_visitor
(v
)
301 if n_type
.collect_text
!= v
.toolcontext
.place_holder_type_name
then return
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
314 redef class AAttrPropdef
315 private fun name
: String
322 private fun type_name
: String
326 if n_kwnullable
!= null then name
= "nullable {name}"
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(", ")}]"
338 private fun deserializer_nclassdef
: nullable AStdClassdef
340 for nclassdef
in n_classdefs
do
341 if nclassdef
isa AStdClassdef and nclassdef
.n_id
.text
== "Deserializer" then
349 private var inits_to_retype
= new Array[AMethPropdef]
351 redef fun is_serialize
do return n_moduledecl
!= null and n_moduledecl
.is_serialize
354 redef class AStdClassdef
355 private fun deserializer_npropdef
: nullable AMethPropdef
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
367 # Is this classed marked `serialize`? in part or fully?
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
375 # Is there a declaration on the classdef or the module?
376 var serialize
= is_serialize
378 if not serialize
and not is_noserialize
then
379 # Is the module marked serialize?
380 serialize
= parent
.as(AModule).is_serialize
383 if serialize
then return true
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