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