nitg: fix tests/sav/nitg with new options added in nitg-s
[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.header
41 v.add_decl("#include <stdlib.h>")
42 v.add_decl("#include <stdio.h>")
43 v.add_decl("#include <string.h>")
44 v.add_decl("#include <gc/gc.h>")
45 v.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
46 v.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
47 v.add_decl("struct class \{ int id; int box_kind; int color; struct vts_table *vts_table; struct type_table *type_table; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
48 v.add_decl("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
49 v.add_decl("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
50 v.add_decl("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
51 v.add_decl("typedef struct \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
52 v.add_decl("extern const char const * class_names[];")
53
54 # Declare global instances
55 v.add_decl("extern int glob_argc;")
56 v.add_decl("extern char **glob_argv;")
57 v.add_decl("extern val *glob_sys;")
58
59 # The main function of the C
60 compiler.compile_main_function
61
62 # compile class structures
63 for m in mainmodule.in_importation.greaters do
64 for mclass in m.intro_mclasses do
65 compiler.compile_class_to_c(mclass)
66 end
67 end
68
69 # compile methods
70 for m in mainmodule.in_importation.greaters do
71 compiler.compile_module_to_c(m)
72 end
73
74 write_and_make(compiler)
75 end
76 end
77
78 class SeparateErasureCompiler
79 super SeparateCompiler
80
81 private var class_ids: HashMap[MClass, Int] = new HashMap[MClass, Int]
82 private var class_tables: nullable Map[MClass, Array[nullable MClass]] = null
83
84 init(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis, mmbuilder: ModelBuilder) do
85 super
86
87 # classes coloration
88 self.class_tables = class_coloring.build_type_tables(mmbuilder.model.mclasses, class_colors)
89
90 # set type unique id
91 for mclass in class_colors.keys do
92 self.class_ids[mclass] = self.class_ids.length
93 end
94
95 # for the class_name and output_class_name methods
96 self.compile_class_names
97 self.compile_box_kinds
98 end
99
100 redef fun compile_class_names do
101 # Build type names table
102 var type_array = new Array[nullable MClass]
103 for t, i in class_ids do
104 if i >= type_array.length then
105 type_array[i] = null
106 end
107 type_array[i] = t
108 end
109
110 var v = self.new_visitor
111 v.add("const char const * class_names[] = \{")
112 for t in type_array do
113 if t == null then
114 v.add("NULL, /* empty */")
115 else
116 v.add("\"{t}\",")
117 end
118 end
119 v.add("\};")
120 end
121
122 redef fun compile_class_to_c(mclass: MClass)
123 do
124 var mtype = mclass.intro.bound_mtype
125 var c_name = mclass.c_name
126
127 var vft = self.method_tables[mclass]
128 var attrs = self.attr_tables[mclass]
129 var class_table = self.class_tables[mclass]
130 var v = self.new_visitor
131
132 v.add_decl("/* runtime class {c_name} */")
133 var idnum = classids.length
134 var idname = "ID_" + c_name
135 self.classids[mtype] = idname
136 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
137
138 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
139 self.header.add_decl("struct class_{c_name} \{")
140 self.header.add_decl("int id;")
141 self.header.add_decl("int box_kind;")
142 self.header.add_decl("int color;")
143 self.header.add_decl("const struct vts_table *vts_table;")
144 self.header.add_decl("struct type_table *type_table;")
145 self.header.add_decl("nitmethod_t vft[{vft.length}];")
146 self.header.add_decl("\};")
147
148 # extern const struct vts_table_X vts_table_X
149 self.header.add_decl("extern const struct vts_table_{c_name} vts_table_{c_name};")
150 self.header.add_decl("struct vts_table_{c_name} \{")
151 self.header.add_decl("struct vts_entry vts[{self.vt_tables[mclass].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.box_kind_of(mclass)}, /* box_kind */")
158 v.add_decl("{self.class_colors[mclass]},")
159 v.add_decl("(const struct vts_table*) &vts_table_{c_name},")
160 v.add_decl("(struct type_table*) &type_table_{c_name},")
161 v.add_decl("\{")
162 for i in [0 .. vft.length[ do
163 var mpropdef = vft[i]
164 if mpropdef == null then
165 v.add_decl("NULL, /* empty */")
166 else
167 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
168 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
169 else
170 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
171 end
172 end
173 end
174 v.add_decl("\}")
175 v.add_decl("\};")
176
177 build_class_vts_table(mclass, v.as(SeparateErasureCompilerVisitor))
178
179 # Build class type table
180 self.header.add_decl("extern const struct type_table_{c_name} type_table_{c_name};")
181 self.header.add_decl("struct type_table_{c_name} \{")
182 self.header.add_decl("int size;")
183 self.header.add_decl("int table[{class_table.length}];")
184 self.header.add_decl("\};")
185
186 v.add_decl("const struct type_table_{c_name} type_table_{c_name} = \{")
187 v.add_decl("{class_table.length},")
188 v.add_decl("\{")
189 for msuper in class_table do
190 if msuper == null then
191 v.add_decl("-1, /* empty */")
192 else
193 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
194 end
195 end
196 v.add_decl("\}")
197 v.add_decl("\};")
198
199 #Build instance struct
200 if mtype.ctype != "val*" then
201 self.header.add_decl("struct instance_{c_name} \{")
202 self.header.add_decl("const struct class *class;")
203 self.header.add_decl("{mtype.ctype} value;")
204 self.header.add_decl("\};")
205
206 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
207 v.add_decl("/* allocate {mtype} */")
208 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
209 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
210 v.add("res->class = (struct class*) &class_{c_name};")
211 v.add("res->value = value;")
212 v.add("return (val*)res;")
213 v.add("\}")
214 return
215 end
216
217 var is_native_array = mclass.name == "NativeArray"
218
219 var sig
220 if is_native_array then
221 sig = "int length"
222 else
223 sig = ""
224 end
225
226 #Build instance struct
227 #extern const struct instance_array__NativeArray instance_array__NativeArray;
228 self.header.add_decl("struct instance_{c_name} \{")
229 self.header.add_decl("const struct class *class;")
230 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
231 if is_native_array then
232 # NativeArrays are just a instance header followed by an array of values
233 self.header.add_decl("val* values[0];")
234 end
235 self.header.add_decl("\};")
236
237
238 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
239 v.add_decl("/* allocate {mtype} */")
240 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
241 var res = v.new_named_var(mtype, "self")
242 res.is_exact = true
243 if is_native_array then
244 var mtype_elt = mtype.arguments.first
245 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
246 else
247 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
248 end
249 v.add("{res}->class = (struct class*) &class_{c_name};")
250
251 self.generate_init_attr(v, res, mtype)
252 v.add("return {res};")
253 v.add("\}")
254
255 generate_check_init_instance(mtype)
256 end
257
258 private fun build_class_vts_table(mclass: MClass, v: SeparateCompilerVisitor) do
259 v.add_decl("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
260 v.add_decl("\{")
261
262 for vt in self.vt_tables[mclass] do
263 if vt == null then
264 v.add_decl("NULL, /* empty */")
265 else
266 var is_null = 0
267 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.bound)
268 while bound isa MNullableType do
269 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
270 is_null = 1
271 end
272 v.add_decl("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
273 end
274 end
275 v.add_decl("\},")
276 v.add_decl("\};")
277 end
278
279 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
280 if mtype == null then
281 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
282 abort
283 end
284 if mtype isa MVirtualType then
285 return mtype.anchor_to(mainmodule, anchor)
286 else if mtype isa MParameterType then
287 return mtype.anchor_to(mainmodule, anchor)
288 else
289 return mtype
290 end
291 end
292
293 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
294 end
295
296 class SeparateErasureCompilerVisitor
297 super SeparateCompilerVisitor
298
299 redef fun init_instance(mtype)
300 do
301 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
302 end
303
304 redef fun type_test(value, mtype)
305 do
306 self.add("/* type test for {value.inspect} isa {mtype} */")
307
308 var res = self.new_var(bool_type)
309
310 var cltype = self.get_name("cltype")
311 self.add_decl("int {cltype};")
312 var idtype = self.get_name("idtype")
313 self.add_decl("int {idtype};")
314 var is_nullable = self.get_name("is_nullable")
315 self.add_decl("short int {is_nullable};")
316 var is_null = self.get_name("is_null")
317 self.add_decl("short int {is_null};")
318
319 var maybe_null = 0
320 if mtype isa MNullableType then
321 mtype = mtype.mtype
322 maybe_null = 1
323 self.add("{is_nullable} = 1;")
324 end
325 if mtype isa MParameterType then
326 # Here we get the bound of the the formal type (eh, erasure...)
327 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
328 if mtype isa MNullableType then
329 mtype = mtype.mtype
330 maybe_null = 1
331 self.add("{is_nullable} = 1;")
332 end
333 end
334 if mtype isa MVirtualType then
335 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
336 #mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
337 #if mtype isa MNullableType then
338 # mtype = mtype.mtype
339 # maybe_null = true
340 #end
341 end
342
343 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
344 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
345 return res
346 end
347
348 var class_ptr
349 var type_table
350 if value.mtype.ctype == "val*" then
351 class_ptr = "{value}->class->"
352 self.add("{is_null} = {value} == NULL;")
353 else
354 var mclass = value.mtype.as(MClassType).mclass
355 class_ptr = "class_{mclass.c_name}."
356 self.add("{is_null} = 0;")
357 end
358
359 if mtype isa MClassType then
360 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
361 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
362 if maybe_null == 0 then
363 self.add("{is_nullable} = 0;")
364 end
365 else if mtype isa MVirtualType then
366 var recv = self.frame.arguments.first
367 var recv_boxed = self.autobox(recv, self.object_type)
368 self.add("{cltype} = {recv_boxed}->class->vts_table->vts[{mtype.mproperty.const_color}].class->color;")
369 self.add("{idtype} = {recv_boxed}->class->vts_table->vts[{mtype.mproperty.const_color}].class->id;")
370 if maybe_null == 0 then
371 self.add("{is_nullable} = {recv_boxed}->class->vts_table->vts[{mtype.mproperty.const_color}].is_nullable;")
372 end
373 else
374 self.debug("type_test({value.inspect}, {mtype})")
375 abort
376 end
377
378 # check color is in table
379 self.add("if({is_null}) \{")
380 self.add("{res} = {is_nullable};")
381 self.add("\} else \{")
382 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
383 self.add("{res} = 0;")
384 self.add("\} else \{")
385 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
386 self.add("\}")
387 self.add("\}")
388
389 return res
390 end
391
392 redef fun class_name_string(value)
393 do
394 var res = self.get_name("var_class_name")
395 self.add_decl("const char *{res};")
396 self.add("{res} = class_names[{value}->class->id];")
397 return res
398 end
399
400 redef fun array_instance(array, elttype)
401 do
402 var nclass = self.get_class("NativeArray")
403 elttype = self.anchor(elttype)
404 var arraytype = self.get_class("Array").get_mtype([elttype])
405 var res = self.init_instance(arraytype)
406 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
407 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
408 nat.is_exact = true
409 self.add("{nat} = NEW_{nclass.c_name}({array.length});")
410 for i in [0..array.length[ do
411 var r = self.autobox(array[i], self.object_type)
412 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
413 end
414 var length = self.int_instance(array.length)
415 self.send(self.get_property("with_native", arraytype), [res, nat, length])
416 self.check_init_instance(res, arraytype)
417 self.add("\}")
418 return res
419 end
420
421 redef fun calloc_array(ret_type, arguments)
422 do
423 var ret = ret_type.as(MClassType)
424 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
425 end
426 end