1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
19 import separate_compiler
20 intrude import coloring
22 redef class ToolContext
24 var opt_erasure
: OptionBool = new OptionBool("Erase generic types", "--erasure")
29 self.option_context
.add_option
(self.opt_erasure
)
33 redef class ModelBuilder
34 redef fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
36 if self.toolcontext
.opt_erasure
.value
then
37 run_separate_erasure_compiler
(mainmodule
, runtime_type_analysis
)
43 fun run_separate_erasure_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
46 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
48 var compiler
= new SeparateErasureCompiler(mainmodule
, runtime_type_analysis
, self)
49 var v
= compiler
.new_visitor
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[];")
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;")
67 # The main function of the C
68 compiler
.compile_main_function
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
)
78 for m
in mainmodule
.in_importation
.greaters
do
79 compiler
.compile_module_to_c
(m
)
82 write_and_make
(compiler
)
86 class SeparateErasureCompiler
87 super SeparateCompiler
89 private var class_ids
: HashMap[MClass, Int] = new HashMap[MClass, Int]
90 private var class_tables
: nullable Map[MClass, Array[nullable MClass]] = null
92 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
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
)
99 var method_coloring
= new MethodColoring(class_coloring
)
100 self.method_colors
= method_coloring
.colorize
101 self.method_tables
= method_coloring
.build_property_tables
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
109 for mclass
in class_colors
.keys
do
110 self.class_ids
[mclass
] = self.class_ids
.length
113 # for the class_name and output_class_name methods
114 self.compile_class_names
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
127 var v
= self.new_visitor
128 v
.add
("const char const * class_names[] = \{")
129 for t
in type_array
do
131 v
.add
("NULL, /* empty */")
139 redef fun compile_class_to_c
(mclass
: MClass)
141 var mtype
= mclass
.intro
.bound_mtype
142 var c_name
= mclass
.c_name
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
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} */")
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}];")
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;")
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} */")
179 self.header
.add_decl
("\};")
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},")
187 for i
in [0 .. vft
.length
[ do
188 var mpropdef
= vft
[i
]
189 if mpropdef
== null then
190 v
.add_decl
("NULL, /* empty */")
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} */")
195 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
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
("\};")
209 v
.add_decl
("const struct type_table_{c_name} type_table_{c_name} = \{")
210 v
.add_decl
("{class_table.length},")
212 for msuper
in class_table
do
213 if msuper
== null then
214 v
.add_decl
("-1, /* empty */")
216 v
.add_decl
("{self.class_ids[msuper]}, /* {msuper} */")
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
("\};")
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;")
240 var is_native_array
= mclass
.name
== "NativeArray"
243 if is_native_array
then
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];")
258 self.header
.add_decl
("\};")
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")
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}));")
270 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
272 v
.add
("{res}->class = (struct class*) &class_{c_name};")
274 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
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
)
283 v
.add
("return {res};")
287 redef fun new_visitor
do return new SeparateErasureCompilerVisitor(self)
290 class SeparateErasureCompilerVisitor
291 super SeparateCompilerVisitor
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
297 if value
.mtype
.ctype
== mtype
.ctype
then
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);")
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} */")
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);")
322 redef fun init_instance
(mtype
)
324 return self.new_expr
("NEW_{mtype.mclass.c_name}()", mtype
)
327 redef fun type_test
(value
, mtype
)
329 var res
= self.new_var
(bool_type
)
330 var boxed
= self.autobox
(value
, self.object_type
)
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};")
337 var maybe_null
= false
338 if mtype
isa MNullableType then
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
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
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;")
362 self.debug
("type_test({value.inspect}, {mtype})")
368 s
= "{boxed} == NULL ||"
370 s
= "{boxed} != NULL &&"
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};")
382 redef fun class_name_string
(value1
)
384 var res
= self.get_name
("var_class_name")
385 self.add_decl
("const char* {res} = class_names[self->class->id];")
389 redef fun array_instance
(array
, elttype
)
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
]))
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};")
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
)
410 redef fun calloc_array
(ret_type
, arguments
)
412 var ret
= ret_type
.as(MClassType)
413 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type
))