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
25 intrude import literal
27 redef class ToolContext
29 # Apply the annotation `serialize_as`
30 var serialization_phase_rename
: Phase = new SerializationPhaseRename(self, null)
32 # Generate serialization and deserialization methods on `auto_serializable` annotated classes.
33 var serialization_phase_pre_model
: Phase = new SerializationPhasePreModel(self,
34 [serialization_phase_rename
])
36 # The second phase of the serialization
37 var serialization_phase_post_model
: Phase = new SerializationPhasePostModel(self,
38 [modelize_property_phase
, serialization_phase_pre_model
])
42 # Is this node annotated to be made serializable?
43 private fun is_serialize
: Bool do return false
45 # Is this node annotated to not be made serializable?
46 private fun is_noserialize
: Bool do return false
49 redef class ADefinition
51 redef fun is_serialize
do
52 return get_annotations
("serialize").not_empty
or
53 get_annotations
("auto_serializable").not_empty
56 redef fun is_noserialize
do
57 return get_annotations
("noserialize").not_empty
61 private class SerializationPhaseRename
64 redef fun process_annotated_node
(node
, nat
)
66 var text
= nat
.n_atid
.n_id
.text
67 if text
!= "serialize_as" then return
69 if not node
isa AAttrPropdef then
70 toolcontext
.error
(node
.location
,
71 "Syntax Error: annotation `{text}` applies only to attributes.")
75 # Can't use `arg_as_string` because it needs the literal phase
77 if args
.length
!= 1 or not args
.first
isa AStringFormExpr then
78 toolcontext
.error
(node
.location
,
79 "Syntax Error: annotation `{text}` expects a single string literal as argument.")
83 var t
= args
.first
.collect_text
84 var val
= t
.substring
(1, t
.length-2
)
85 node
.serialize_name
= val
89 private class SerializationPhasePreModel
92 redef fun process_annotated_node
(node
, nat
)
94 # Skip if we are not interested
95 var text
= nat
.n_atid
.n_id
.text
96 var serialize
= text
== "auto_serializable" or text
== "serialize"
97 var noserialize
= text
== "noserialize"
98 if not (serialize
or noserialize
) then return
100 # Check legality of annotation
101 if node
isa AModuledecl then
102 if noserialize
then toolcontext
.error
(node
.location
, "Syntax Error: superfluous use of `{text}`, by default a module is `{text}`")
104 else if not (node
isa AStdClassdef or node
isa AAttrPropdef) then
105 toolcontext
.error
(node
.location
,
106 "Syntax Error: only a class, a module or an attribute can be annotated with `{text}`.")
108 else if serialize
and node
.is_noserialize
then
109 toolcontext
.error
(node
.location
,
110 "Syntax Error: an entity cannot be both `{text}` and `noserialize`.")
112 else if node
.as(Prod).get_annotations
(text
).length
> 1 then
113 toolcontext
.warning
(node
.location
, "useless-{text}",
114 "Warning: duplicated annotation `{text}`.")
117 # Check the `serialize` state of the parent
118 if not node
isa AModuledecl then
119 var up_serialize
= false
120 var up
: nullable ANode = node
125 else if up
.is_serialize
then
128 else if up
.is_noserialize
then
133 # Check for useless double declarations
134 if serialize
and up_serialize
then
135 toolcontext
.warning
(node
.location
, "useless-serialize",
136 "Warning: superfluous use of `{text}`.")
137 else if noserialize
and not up_serialize
then
138 toolcontext
.warning
(node
.location
, "useless-noserialize",
139 "Warning: superfluous use of `{text}`.")
144 redef fun process_nclassdef
(nclassdef
)
146 if not nclassdef
isa AStdClassdef then return
148 var serialize_by_default
= nclassdef
.how_serialize
150 if serialize_by_default
!= null then
152 # Add `super Serializable`
153 var sc
= toolcontext
.parse_superclass
("Serializable")
154 sc
.location
= nclassdef
.location
155 nclassdef
.n_propdefs
.add sc
158 var per_attribute
= not serialize_by_default
159 generate_serialization_method
(nclassdef
, per_attribute
)
160 generate_deserialization_init
(nclassdef
)
164 redef fun process_nmodule
(nmodule
)
166 # Clear the cache of constructors to review before adding to it
167 nmodule
.inits_to_retype
.clear
169 # collect all classes
170 var auto_serializable_nclassdefs
= nmodule
.auto_serializable_nclassdefs
171 if not auto_serializable_nclassdefs
.is_empty
then
172 generate_deserialization_method
(nmodule
, auto_serializable_nclassdefs
)
176 # Implement `core_serialize_to` on `nclassdef`
178 # Are attributes serialized on demand `per_attribute` with `serialize`?
179 # Otherwise they are serialized by default, and we check instead for `noserialize`.
180 fun generate_serialization_method
(nclassdef
: AClassdef, per_attribute
: Bool)
182 var npropdefs
= nclassdef
.n_propdefs
184 var code
= new Array[String]
185 code
.add
"redef fun core_serialize_to(v)"
189 for attribute
in npropdefs
do if attribute
isa AAttrPropdef then
191 # Is `attribute` to be skipped?
192 if (per_attribute
and not attribute
.is_serialize
) or
193 attribute
.is_noserialize
then continue
195 code
.add
" v.serialize_attribute(\"{attribute.serialize_name}\
", {attribute.name})"
200 # Create method Node and add it to the AST
201 npropdefs
.push
(toolcontext
.parse_propdef
(code
.join
("\n")))
204 # Add an empty constructor to the automated nclassdef
206 # Will be filled by `SerializationPhasePostModel`.
207 fun generate_deserialization_init
(nclassdef
: AClassdef)
209 var npropdefs
= nclassdef
.n_propdefs
211 # Do not insert a `from_deserializer` if it already exists
212 for npropdef
in npropdefs
do
213 if npropdef
isa AMethPropdef then
214 var methid
= npropdef
.n_methid
215 if methid
!= null and methid
.collect_text
== "from_deserializer" then
222 redef init from_deserializer(v: Deserializer) do abort"""
224 var npropdef
= toolcontext
.parse_propdef
(code
).as(AMethPropdef)
225 npropdefs
.add npropdef
226 nclassdef
.parent
.as(AModule).inits_to_retype
.add npropdef
229 # Add an empty `Deserializer::deserialize_class_intern`
231 # Will be filled by `SerializationPhasePostModel`.
232 fun generate_deserialization_method
(nmodule
: AModule, nclassdefs
: Array[AStdClassdef])
234 var code
= new Array[String]
236 var deserializer_nclassdef
= nmodule
.deserializer_nclassdef
237 var deserializer_npropdef
238 if deserializer_nclassdef
== null then
240 code
.add
"redef class Deserializer"
241 deserializer_npropdef
= null
243 deserializer_npropdef
= deserializer_nclassdef
.deserializer_npropdef
246 if deserializer_npropdef
== null then
247 # create the property
248 code
.add
" redef fun deserialize_class_intern(name) do abort"
250 toolcontext
.error
(deserializer_npropdef
.location
, "Error: `Deserializer::deserialize_class_intern` is generated and must not be defined, use `deserialize_class` instead.")
254 if deserializer_nclassdef
== null then
256 nmodule
.n_classdefs
.add toolcontext
.parse_classdef
(code
.join
("\n"))
258 deserializer_nclassdef
.n_propdefs
.add
(toolcontext
.parse_propdef
(code
.join
("\n")))
263 private class SerializationPhasePostModel
266 # Fill the deserialization init `from_deserializer` and `Deserializer.deserialize_class_intern`
267 redef fun process_nmodule
(nmodule
)
269 for npropdef
in nmodule
.inits_to_retype
do
270 var nclassdef
= npropdef
.parent
271 assert nclassdef
isa AStdClassdef
273 var serialize_by_default
= nclassdef
.how_serialize
274 assert serialize_by_default
!= null
276 var per_attribute
= not serialize_by_default
277 fill_deserialization_init
(nclassdef
, npropdef
, per_attribute
)
280 # collect all classes
281 var auto_serializable_nclassdefs
= nmodule
.auto_serializable_nclassdefs
282 if not auto_serializable_nclassdefs
.is_empty
then
283 fill_deserialization_method
(nmodule
, auto_serializable_nclassdefs
)
287 # Fill the constructor to the generated `init_npropdef` of `nclassdef`
288 fun fill_deserialization_init
(nclassdef
: AClassdef, init_npropdef
: AMethPropdef, per_attribute
: Bool)
290 var code
= new Array[String]
292 redef init from_deserializer(v: Deserializer)
295 v.notify_of_creation self
298 for attribute
in nclassdef
.n_propdefs
do
299 if not attribute
isa AAttrPropdef then continue
301 # Is `attribute` to be skipped?
302 if (per_attribute
and not attribute
.is_serialize
) or
303 attribute
.is_noserialize
then continue
305 var mtype
= attribute
.mtype
306 if mtype
== null then continue
307 var type_name
= mtype
.to_s
308 var name
= attribute
.name
310 if type_name
== "nullable Object" then
313 self.{{{name}}} = v.deserialize_attribute("{{{attribute.serialize_name}}}", "{{{type_name}}}")
316 var {{{name}}} = v.deserialize_attribute("{{{attribute.serialize_name}}}", "{{{type_name}}}")
317 if not {{{name}}} isa {{{type_name}}} then
318 v.errors.add new AttributeTypeError(self, "{{{attribute.serialize_name}}}", {{{name}}}, "{{{type_name}}}")
319 if v.keep_going == false then return
321 self.{{{name}}} = {{{name}}}
328 # Replace the body of the constructor
329 var npropdef
= toolcontext
.parse_propdef
(code
.join
("\n")).as(AMethPropdef)
330 init_npropdef
.n_block
= npropdef
.n_block
332 # Run the literal phase on the generated code
333 var v
= new LiteralVisitor(toolcontext
)
334 v
.enter_visit
(npropdef
.n_block
)
337 # Fill the abstract serialization service
338 fun fill_deserialization_method
(nmodule
: AModule, nclassdefs
: Array[AStdClassdef])
340 var deserializer_nclassdef
= nmodule
.deserializer_nclassdef
341 if deserializer_nclassdef
== null then return
342 var deserializer_npropdef
= deserializer_nclassdef
.deserializer_npropdef
343 if deserializer_npropdef
== null then return
345 # Collect local types expected to be deserialized
346 var types_to_deserialize
= new Set[String]
348 ## Local serializable standard class without parameters
349 for nclassdef
in nclassdefs
do
350 var mclass
= nclassdef
.mclass
351 if mclass
== null then continue
353 if mclass
.arity
== 0 and mclass
.kind
== concrete_kind
then
354 types_to_deserialize
.add mclass
.name
358 ## Static parametized types on serializable attributes
359 for nclassdef
in nmodule
.n_classdefs
do
360 if not nclassdef
isa AStdClassdef then continue
362 for attribute
in nclassdef
.n_propdefs
do
363 if not attribute
isa AAttrPropdef then continue
365 var serialize_by_default
= nclassdef
.how_serialize
366 if serialize_by_default
== null then continue
367 var per_attribute
= not serialize_by_default
369 # Is `attribute` to be skipped?
370 if (per_attribute
and not attribute
.is_serialize
) or
371 attribute
.is_noserialize
then continue
373 var mtype
= attribute
.mtype
374 if mtype
== null then continue
375 if mtype
isa MNullableType then mtype
= mtype
.mtype
377 if mtype
isa MClassType and mtype
.mclass
.arity
> 0 and
378 mtype
.mclass
.kind
== concrete_kind
and not mtype
.need_anchor
then
380 # Check is a `Serializable`
381 var mmodule
= nmodule
.mmodule
382 if mmodule
== null then continue
384 var greaters
= mtype
.mclass
.in_hierarchy
(mmodule
).greaters
385 var is_serializable
= false
386 for sup
in greaters
do if sup
.name
== "Serializable" then
387 is_serializable
= true
391 if is_serializable
then types_to_deserialize
.add mtype
.to_s
396 # Build implementation code
397 var code
= new Array[String]
398 code
.add
"redef fun deserialize_class_intern(name)"
401 for name
in types_to_deserialize
do
402 code
.add
" if name == \"{name}\
" then return new {name}.from_deserializer(self)"
405 code
.add
" return super"
408 # Replace the body of the constructor
409 var npropdef
= toolcontext
.parse_propdef
(code
.join
("\n")).as(AMethPropdef)
410 deserializer_npropdef
.n_block
= npropdef
.n_block
412 # Run the literal phase on the generated code
413 var v
= new LiteralVisitor(toolcontext
)
414 v
.enter_visit
(npropdef
.n_block
)
418 redef class AAttrPropdef
419 private fun name
: String do return n_id2
.text
421 # Name of this attribute in the serialized format
422 private var serialize_name
: String = name
is lazy
426 private fun type_name
: String
428 var name
= n_qid
.n_id
.text
430 if n_kwnullable
!= null then name
= "nullable {name}"
433 if not types
.is_empty
then
434 var params
= new Array[String]
435 for t
in types
do params
.add
(t
.type_name
)
436 return "{name}[{params.join(", ")}]"
442 private fun deserializer_nclassdef
: nullable AStdClassdef
444 for nclassdef
in n_classdefs
do
445 if not nclassdef
isa AStdClassdef then continue
446 var n_qid
= nclassdef
.n_qid
447 if n_qid
!= null and n_qid
.n_id
.text
== "Deserializer" then return nclassdef
453 private var inits_to_retype
= new Array[AMethPropdef]
455 redef fun is_serialize
457 var n_moduledecl
= n_moduledecl
458 return n_moduledecl
!= null and n_moduledecl
.is_serialize
461 # `AStdClassdef` marked as serializable, itself or one of theur attribute
462 private var auto_serializable_nclassdefs
: Array[AStdClassdef] is lazy
do
463 var array
= new Array[AStdClassdef]
464 for nclassdef
in n_classdefs
do
465 if nclassdef
isa AStdClassdef and nclassdef
.how_serialize
!= null then
473 redef class AStdClassdef
474 private fun deserializer_npropdef
: nullable AMethPropdef
476 for npropdef
in n_propdefs
do if npropdef
isa AMethPropdef then
477 var id
= npropdef
.n_methid
478 if id
isa AIdMethid and id
.n_id
.text
== "deserialize_class_intern" then
486 # Is this classed marked `serialize`? in part or fully?
488 # This method returns 3 possible values:
489 # * `null`, this class is not to be serialized.
490 # * `true`, the attributes of this class are to be serialized by default.
491 # * `false`, the attributes of this class are to be serialized on demand only.
492 fun how_serialize
: nullable Bool
494 # Is there a declaration on the classdef or the module?
495 var serialize
= is_serialize
497 if not serialize
and not is_noserialize
then
498 # Is the module marked serialize?
499 serialize
= parent
.as(AModule).is_serialize
502 if serialize
then return true
504 if not serialize
then
505 # Is there an attribute marked serialize?
506 for npropdef
in n_propdefs
do
507 if npropdef
.is_serialize
then