a1eb934b6ef3f1b38b7da3f02ae56dd0212b7759
[nit.git] / src / compiling / icode_generator.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Generates ICode as an output format
18 package icode_generator
19
20 import compiling_base
21 import program
22 import analysis
23
24 redef class Program
25 # Generates ICode for the whole program
26 fun generate_icode_files do
27 tc.compdir.mkdir
28
29 with_each_live_local_classes !action(c) do
30 c.generate_icode_file(tc.compdir.as(not null))
31 end
32 end
33 end
34
35 # A class to dump ICode to a file
36 class FileICodeDumper
37 super ICodeDumper
38 var _file: OFStream
39
40 init(f: OFStream) do
41 # We don't want to output line numbers and locations
42 super(false, false)
43 _file = f
44 end
45
46 redef fun write(s) do
47 for i in [0..indent_level[ do
48 _file.write(" ")
49 end
50 _file.write(s)
51 _file.write("\n")
52 end
53 end
54
55 redef class MMLocalClass
56 # Generates ICode for all properties of this class in a file
57 fun generate_icode_file(dir: String) do
58 var file = new OFStream.open("{dir}/{self}.icode")
59 if primitive_info == null then
60 # Initialization methods
61 if init_var_iroutine != null then
62 var icd = new FileICodeDumper(file)
63 icd.indent
64 file.write("Init var iroutine::\n")
65 init_var_iroutine.dump(icd)
66 file.write("\n\n")
67 end
68 if checknew_iroutine != null then
69 var icd = new FileICodeDumper(file)
70 icd.indent
71 file.write("Check new instance iroutine::\n")
72 checknew_iroutine.dump(icd)
73 file.write("\n\n")
74 end
75
76 # 'new' methods
77 for pg in global_properties do
78 if not pg.is_init_for(self) then continue
79 var p = self[pg]
80 assert p isa MMMethod
81 var icd = new FileICodeDumper(file)
82 icd.indent
83 file.write("New instance:: {p.full_name}\n")
84 new_instance_iroutine[p].dump(icd)
85 file.write("\n\n")
86 end
87 end
88
89 # Other methods
90 for pg in global_properties do
91 var p = self[pg]
92 if p.local_class == self and p isa MMMethod then
93 p.generate_icode(file)
94 end
95 end
96 file.close
97 end
98 end
99
100 redef class MMMethod
101 # Generates ICode for this method with a little header
102 fun generate_icode(file: OFStream) do
103 var icd = new FileICodeDumper(file)
104 icd.indent
105 file.write("Method:: {full_name}\n")
106 iroutine.dump(icd)
107 file.write("\n\n")
108 end
109 end