Merge commit 'b7e675f'
[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
25 redef class ToolContext
26 var serialization_phase: Phase = new SerializationPhase(self, null)
27 end
28
29 # TODO automaticaly add Serializable as a super class
30 # TODO Sequences
31 # TODO add annotations on attributes (volatile, sensitive or do_not_serialize?)
32 private class SerializationPhase
33 super Phase
34
35 redef fun process_annotated_node(nclassdef, nat)
36 do
37 # Skip if we are not interested
38 if nat.n_atid.n_id.text != "auto_serializable" then return
39 if not nclassdef isa AStdClassdef then
40 toolcontext.error(nclassdef.location, "Syntax error: only a concrete class can be automatically serialized.")
41 return
42 end
43
44 generate_serialization_method(nclassdef)
45 end
46
47 private fun generate_serialization_method(nclassdef: AClassdef)
48 do
49 var npropdefs = nclassdef.n_propdefs
50
51 var code = new Array[String]
52 code.add "redef fun core_serialize_to(v)"
53 code.add "do"
54 code.add " super"
55
56 for attribute in npropdefs do if attribute isa AAttrPropdef then
57 var name
58 if attribute.n_id == null then
59 name = attribute.n_id2.text
60 else name = attribute.n_id.text
61
62 code.add " v.serialize_attribute(\"{name}\", {name})"
63 end
64
65 code.add "end"
66
67 # Create method Node and add it to the AST
68 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
69 end
70 end