nitg: move engine selection to nitg.nit
[nit.git] / src / separate_erasure_compiler.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 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
17
18
19 import separate_compiler
20 intrude import coloring
21
22 redef class ToolContext
23 # --erasure
24 var opt_erasure: OptionBool = new OptionBool("Erase generic types", "--erasure")
25
26 redef init
27 do
28 super
29 self.option_context.add_option(self.opt_erasure)
30 end
31 end
32
33 redef class ModelBuilder
34 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
35 do
36 var time0 = get_time
37 self.toolcontext.info("*** COMPILING TO C ***", 1)
38
39 var compiler = new SeparateErasureCompiler(mainmodule, runtime_type_analysis, self)
40 var v = compiler.new_visitor
41 compiler.header = v
42 v.add_decl("#include <stdlib.h>")
43 v.add_decl("#include <stdio.h>")
44 v.add_decl("#include <string.h>")
45 v.add_decl("#include <gc/gc.h>")
46 v.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
47 v.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
48 v.add_decl("struct class \{ int id; int color; struct type_table *type_table; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
49 v.add_decl("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
50 v.add_decl("typedef struct \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
51 v.add_decl("extern const char const * class_names[];")
52
53 # Declare global instances
54 v.add_decl("extern int glob_argc;")
55 v.add_decl("extern char **glob_argv;")
56 v.add_decl("extern val *glob_sys;")
57
58 # The main function of the C
59 compiler.compile_main_function
60
61 # compile class structures
62 for m in mainmodule.in_importation.greaters do
63 for mclass in m.intro_mclasses do
64 compiler.compile_class_to_c(mclass)
65 end
66 end
67
68 # compile methods
69 for m in mainmodule.in_importation.greaters do
70 compiler.compile_module_to_c(m)
71 end
72
73 write_and_make(compiler)
74 end
75 end
76
77 class SeparateErasureCompiler
78 super SeparateCompiler
79
80 private var class_ids: HashMap[MClass, Int] = new HashMap[MClass, Int]
81 private var class_tables: nullable Map[MClass, Array[nullable MClass]] = null
82
83 init(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis, mmbuilder: ModelBuilder) do
84 # classes coloration
85 var class_coloring = new ClassColoring(mainmodule)
86 self.class_colors = class_coloring.colorize(mmbuilder.model.mclasses)
87 self.class_tables = class_coloring.build_type_tables(mmbuilder.model.mclasses, class_colors)
88
89 # methods coloration
90 var method_coloring = new MethodColoring(class_coloring)
91 self.method_colors = method_coloring.colorize
92 self.method_tables = method_coloring.build_property_tables
93
94 # attributes coloration
95 var attribute_coloring = new AttributeColoring(class_coloring)
96 self.attr_colors = attribute_coloring.colorize
97 self.attr_tables = attribute_coloring.build_property_tables
98
99 # set type unique id
100 for mclass in class_colors.keys do
101 self.class_ids[mclass] = self.class_ids.length
102 end
103
104 # for the class_name and output_class_name methods
105 self.compile_class_names
106 end
107
108 redef fun compile_class_names do
109 # Build type names table
110 var type_array = new Array[nullable MClass]
111 for t, i in class_ids do
112 if i >= type_array.length then
113 type_array[i] = null
114 end
115 type_array[i] = t
116 end
117
118 var v = self.new_visitor
119 v.add("const char const * class_names[] = \{")
120 for t in type_array do
121 if t == null then
122 v.add("NULL, /* empty */")
123 else
124 v.add("\"{t}\",")
125 end
126 end
127 v.add("\};")
128 end
129
130 redef fun compile_class_to_c(mclass: MClass)
131 do
132 var mtype = mclass.intro.bound_mtype
133 var c_name = mclass.c_name
134
135 var vft = self.method_tables[mclass]
136 var attrs = self.attr_tables[mclass]
137 var class_table = self.class_tables[mclass]
138 var v = self.new_visitor
139
140 v.add_decl("/* runtime class {c_name} */")
141 var idnum = classids.length
142 var idname = "ID_" + c_name
143 self.classids[mtype] = idname
144 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
145
146 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
147 self.header.add_decl("struct class_{c_name} \{")
148 self.header.add_decl("int id;")
149 self.header.add_decl("int color;")
150 self.header.add_decl("struct type_table *type_table;")
151 self.header.add_decl("nitmethod_t vft[{vft.length}];")
152 self.header.add_decl("\};")
153
154 # Build class vft
155 v.add_decl("const struct class_{c_name} class_{c_name} = \{")
156 v.add_decl("{self.class_ids[mclass]},")
157 v.add_decl("{self.class_colors[mclass]},")
158 v.add_decl("(struct type_table*) &type_table_{c_name},")
159 v.add_decl("\{")
160 for i in [0 .. vft.length[ do
161 var mpropdef = vft[i]
162 if mpropdef == null then
163 v.add_decl("NULL, /* empty */")
164 else
165 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
166 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
167 else
168 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
169 end
170 end
171 end
172 v.add_decl("\}")
173 v.add_decl("\};")
174
175 # Build class type table
176 self.header.add_decl("extern const struct type_table_{c_name} type_table_{c_name};")
177 self.header.add_decl("struct type_table_{c_name} \{")
178 self.header.add_decl("int size;")
179 self.header.add_decl("int table[{class_table.length}];")
180 self.header.add_decl("\};")
181
182 v.add_decl("const struct type_table_{c_name} type_table_{c_name} = \{")
183 v.add_decl("{class_table.length},")
184 v.add_decl("\{")
185 for msuper in class_table do
186 if msuper == null then
187 v.add_decl("-1, /* empty */")
188 else
189 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
190 end
191 end
192 v.add_decl("\}")
193 v.add_decl("\};")
194
195 #Build instance struct
196 if mtype.ctype != "val*" then
197 self.header.add_decl("struct instance_{c_name} \{")
198 self.header.add_decl("const struct class *class;")
199 self.header.add_decl("{mtype.ctype} value;")
200 self.header.add_decl("\};")
201
202 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
203 v.add_decl("/* allocate {mtype} */")
204 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
205 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
206 v.add("res->class = (struct class*) &class_{c_name};")
207 v.add("res->value = value;")
208 v.add("return (val*)res;")
209 v.add("\}")
210 return
211 end
212
213 var is_native_array = mclass.name == "NativeArray"
214
215 var sig
216 if is_native_array then
217 sig = "int length"
218 else
219 sig = ""
220 end
221
222 #Build instance struct
223 #extern const struct instance_array__NativeArray instance_array__NativeArray;
224 self.header.add_decl("struct instance_{c_name} \{")
225 self.header.add_decl("const struct class *class;")
226 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
227 if is_native_array then
228 # NativeArrays are just a instance header followed by an array of values
229 self.header.add_decl("val* values[0];")
230 end
231 self.header.add_decl("\};")
232
233
234 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
235 v.add_decl("/* allocate {mtype} */")
236 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
237 var res = v.new_named_var(mtype, "self")
238 res.is_exact = true
239 if is_native_array then
240 var mtype_elt = mtype.arguments.first
241 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
242 else
243 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
244 end
245 v.add("{res}->class = (struct class*) &class_{c_name};")
246
247 for cd in mtype.collect_mclassdefs(self.mainmodule)
248 do
249 var n = self.modelbuilder.mclassdef2nclassdef[cd]
250 for npropdef in n.n_propdefs do
251 if npropdef isa AAttrPropdef then
252 npropdef.init_expr(v, res)
253 end
254 end
255 end
256 v.add("return {res};")
257 v.add("\}")
258 end
259
260 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
261 end
262
263 class SeparateErasureCompilerVisitor
264 super SeparateCompilerVisitor
265
266 redef fun init_instance(mtype)
267 do
268 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
269 end
270
271 redef fun type_test(value, mtype)
272 do
273 var res = self.new_var(bool_type)
274
275 var cltype = self.get_name("cltype")
276 self.add_decl("int {cltype};")
277 var idtype = self.get_name("idtype")
278 self.add_decl("int {idtype};")
279
280 var maybe_null = false
281 if mtype isa MNullableType then
282 mtype = mtype.mtype
283 maybe_null = true
284 end
285 if mtype isa MParameterType then
286 # Here we get the bound of the the formal type (eh, erasure...)
287 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
288 if mtype isa MNullableType then
289 mtype = mtype.mtype
290 maybe_null = true
291 end
292 end
293 if mtype isa MVirtualType then
294 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
295 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
296 if mtype isa MNullableType then
297 mtype = mtype.mtype
298 maybe_null = true
299 end
300 end
301
302 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
303 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
304 return res
305 end
306
307 var type_table
308 if value.mtype.ctype == "val*" then
309 type_table = "{value}->class->type_table"
310 else
311 var mclass = value.mtype.as(MClassType).mclass
312 type_table = "type_table_{mclass.c_name}"
313 end
314
315 if mtype isa MClassType then
316 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
317 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
318 else
319 self.debug("type_test({value.inspect}, {mtype})")
320 abort
321 end
322
323 var s: String
324 if maybe_null then
325 s = "{value} == NULL ||"
326 else
327 s = "{value} != NULL &&"
328 end
329 # check color is in table
330 self.add("if({value} != NULL && {cltype} >= {type_table}->size) \{")
331 self.add("{res} = 0;")
332 self.add("\} else \{")
333 self.add("{res} = {s} {type_table}->table[{cltype}] == {idtype};")
334 self.add("\}")
335
336 return res
337 end
338
339 redef fun class_name_string(value1)
340 do
341 var res = self.get_name("var_class_name")
342 self.add_decl("const char* {res} = class_names[self->class->id];")
343 return res
344 end
345
346 redef fun array_instance(array, elttype)
347 do
348 var nclass = self.get_class("NativeArray")
349 elttype = self.anchor(elttype)
350 var arraytype = self.get_class("Array").get_mtype([elttype])
351 var res = self.init_instance(arraytype)
352 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
353 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
354 nat.is_exact = true
355 self.add("{nat} = NEW_{nclass.c_name}({array.length});")
356 for i in [0..array.length[ do
357 var r = self.autobox(array[i], self.object_type)
358 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
359 end
360 var length = self.int_instance(array.length)
361 self.send(self.get_property("with_native", arraytype), [res, nat, length])
362 self.check_init_instance(res)
363 self.add("\}")
364 return res
365 end
366
367 redef fun calloc_array(ret_type, arguments)
368 do
369 var ret = ret_type.as(MClassType)
370 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
371 end
372 end