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