e04a4f48dd238ad3790f58c3acc2abe6f3bedbab
[nit.git] / src / frontend / deriving.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Injection of automatic method definitions for standard methods, based on the attributes of the classes
16 #
17 # This phase is only a proof of concept and is inherently fragile:
18 #
19 # * syntactic code injection without semantic checking
20 # * ignorance of name conflicts
21 # * attributes are syntactically and locally collected
22 module deriving
23
24 private import parser_util
25 import modelize
26 private import annotation
27
28 redef class ToolContext
29 # Main phase of `deriving`
30 var deriving_phase: Phase = new DerivingPhase(self, null)
31 end
32
33 private class DerivingPhase
34 super Phase
35
36 redef fun process_annotated_node(nclassdef, nat)
37 do
38 if nat.name == "auto_inspect" then
39 if not nclassdef isa AStdClassdef then
40 toolcontext.error(nclassdef.location, "Syntax error: only a concrete class can be `{nat.name}`.")
41 else
42 generate_inspect_method(nclassdef)
43 end
44 end
45 end
46
47 fun generate_inspect_method(nclassdef: AClassdef)
48 do
49 var npropdefs = nclassdef.n_propdefs
50
51 var code = new Array[String]
52 code.add "redef fun inspect"
53 code.add "do"
54 code.add " var res = super"
55 code.add " res = res.substring(0,res.length-1)"
56
57 for attribute in npropdefs do if attribute isa AAttrPropdef then
58 var name = attribute.n_id2.text
59 code.add """ res += " {{{name}}}: {self.{{{name}}}.inspect}""""
60 end
61
62 code.add " res += \">\""
63 code.add " return res"
64 code.add "end"
65
66 # Create method Node and add it to the AST
67 npropdefs.push(toolcontext.parse_propdef(code.join("\n")))
68 end
69 end