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
21 redef class ToolContext
23 var opt_erasure
: OptionBool = new OptionBool("Erase generic types", "--erasure")
25 # --no-check-erasure-cast
26 var opt_no_check_erasure_cast
: OptionBool = new OptionBool("Disable implicit casts on unsafe return with erasure-typing policy (dangerous)", "--no-check-erasure-cast")
31 self.option_context
.add_option
(self.opt_erasure
, self.opt_no_check_erasure_cast
)
35 redef class ModelBuilder
36 fun run_separate_erasure_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
39 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
41 var compiler
= new SeparateErasureCompiler(mainmodule
, runtime_type_analysis
, self)
42 compiler
.compile_header
44 # compile class structures
45 for m
in mainmodule
.in_importation
.greaters
do
46 for mclass
in m
.intro_mclasses
do
47 compiler
.compile_class_to_c
(mclass
)
51 # The main function of the C
52 compiler
.compile_main_function
55 for m
in mainmodule
.in_importation
.greaters
do
56 compiler
.compile_module_to_c
(m
)
59 write_and_make
(compiler
)
63 class SeparateErasureCompiler
64 super SeparateCompiler
66 private var class_ids
: HashMap[MClass, Int] = new HashMap[MClass, Int]
67 private var class_colors
: Map[MClass, Int]
68 private var class_tables
: Map[MClass, Array[nullable MClass]]
70 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
71 var mclasses
= new HashSet[MClass]
72 mclasses
.add_all
(mmbuilder
.model
.mclasses
)
75 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
77 for mclass
in mclasses
do
78 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
81 var class_coloring
= new ClassModPerfectHashing(mainmodule
)
82 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
83 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
85 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
86 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
88 for mclass
in mclasses
do
89 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
92 var class_coloring
= new ClassAndPerfectHashing(mainmodule
)
93 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
94 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
96 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
99 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
100 class_coloring
= new NaiveClassColoring(mainmodule
)
102 class_coloring
= new ClassColoring(mainmodule
)
105 for mclass
in mclasses
do
106 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
108 self.class_colors
= class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
109 self.class_tables
= class_coloring
.build_type_tables
(modelbuilder
.model
.mclasses
, class_colors
)
113 redef fun compile_header_structs
do
114 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
115 self.compile_header_attribute_structs
116 self.header
.add_decl
("struct class \{ int id; const char *name; 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. */")
117 self.header
.add_decl
("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
118 self.header
.add_decl
("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
120 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
121 self.header
.add_decl
("struct vts_table \{ int mask; struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
123 self.header
.add_decl
("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
126 self.header
.add_decl
("typedef struct val \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
129 redef fun compile_class_to_c
(mclass
: MClass)
131 var mtype
= mclass
.intro
.bound_mtype
132 var c_name
= mclass
.c_name
134 var vft
= self.method_tables
[mclass
]
135 var attrs
= self.attr_tables
[mclass
]
136 var class_table
= self.class_tables
[mclass
]
137 var v
= self.new_visitor
139 v
.add_decl
("/* runtime class {c_name} */")
140 var idnum
= classids
.length
141 var idname
= "ID_" + c_name
142 self.classids
[mtype
] = idname
143 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
145 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
146 self.header
.add_decl
("struct class_{c_name} \{")
147 self.header
.add_decl
("int id;")
148 self.header
.add_decl
("const char *name;")
149 self.header
.add_decl
("int box_kind;")
150 self.header
.add_decl
("int color;")
151 self.header
.add_decl
("const struct vts_table *vts_table;")
152 self.header
.add_decl
("struct type_table *type_table;")
153 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
154 self.header
.add_decl
("\};")
157 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
158 v
.add_decl
("{self.class_ids[mclass]},")
159 v
.add_decl
("\"{mclass.name}\
", /* class_name_string */")
160 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
161 v
.add_decl
("{self.class_colors[mclass]},")
162 if build_class_vts_table
(mclass
) then
163 v
.add_decl
("(const struct vts_table*) &vts_table_{c_name},")
167 v
.add_decl
("(struct type_table*) &type_table_{c_name},")
169 for i
in [0 .. vft
.length
[ do
170 var mpropdef
= vft
[i
]
171 if mpropdef
== null then
172 v
.add_decl
("NULL, /* empty */")
174 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
175 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
177 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
184 # Build class type table
185 self.header
.add_decl
("extern const struct type_table_{c_name} type_table_{c_name};")
186 self.header
.add_decl
("struct type_table_{c_name} \{")
187 self.header
.add_decl
("int size;")
188 self.header
.add_decl
("int table[{class_table.length}];")
189 self.header
.add_decl
("\};")
191 v
.add_decl
("const struct type_table_{c_name} type_table_{c_name} = \{")
192 v
.add_decl
("{class_table.length},")
194 for msuper
in class_table
do
195 if msuper
== null then
196 v
.add_decl
("-1, /* empty */")
198 v
.add_decl
("{self.class_ids[msuper]}, /* {msuper} */")
204 #Build instance struct
205 if mtype
.ctype
!= "val*" then
206 self.header
.add_decl
("struct instance_{c_name} \{")
207 self.header
.add_decl
("const struct class *class;")
208 self.header
.add_decl
("{mtype.ctype} value;")
209 self.header
.add_decl
("\};")
211 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
212 v
.add_decl
("/* allocate {mtype} */")
213 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
214 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
215 v
.add
("res->class = (struct class*) &class_{c_name};")
216 v
.add
("res->value = value;")
217 v
.add
("return (val*)res;")
222 var is_native_array
= mclass
.name
== "NativeArray"
225 if is_native_array
then
231 #Build instance struct
232 #extern const struct instance_array__NativeArray instance_array__NativeArray;
233 self.header
.add_decl
("struct instance_{c_name} \{")
234 self.header
.add_decl
("const struct class *class;")
235 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
236 if is_native_array
then
237 # NativeArrays are just a instance header followed by an array of values
238 self.header
.add_decl
("val* values[0];")
240 self.header
.add_decl
("\};")
243 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
244 v
.add_decl
("/* allocate {mtype} */")
245 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
246 var res
= v
.new_named_var
(mtype
, "self")
248 if is_native_array
then
249 var mtype_elt
= mtype
.arguments
.first
250 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
252 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
254 v
.add
("{res}->class = (struct class*) &class_{c_name};")
256 self.generate_init_attr
(v
, res
, mtype
)
257 v
.add
("return {res};")
260 generate_check_init_instance
(mtype
)
263 private fun build_class_vts_table
(mclass
: MClass): Bool do
264 if self.vt_tables
[mclass
].is_empty
then return false
266 self.header
.add_decl
("extern const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name};")
267 self.header
.add_decl
("struct vts_table_{mclass.c_name} \{")
268 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
269 self.header
.add_decl
("int mask;")
271 self.header
.add_decl
("struct vts_entry vts[{self.vt_tables[mclass].length}];")
272 self.header
.add_decl
("\};")
275 v
.add_decl
("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
276 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
277 v
.add_decl
("{vt_masks[mclass]},")
281 for vt
in self.vt_tables
[mclass
] do
283 v
.add_decl
("\{-1, NULL\}, /* empty */")
286 var bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, vt
.bound
)
287 while bound
isa MNullableType do
288 bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, bound
.mtype
)
291 v
.add_decl
("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
299 private fun retrieve_vt_bound
(anchor
: MClassType, mtype
: nullable MType): MType do
300 if mtype
== null then
301 print
"NOT YET IMPLEMENTED: retrieve_vt_bound on null"
304 if mtype
isa MVirtualType then
305 return mtype
.anchor_to
(mainmodule
, anchor
)
306 else if mtype
isa MParameterType then
307 return mtype
.anchor_to
(mainmodule
, anchor
)
313 redef fun new_visitor
do return new SeparateErasureCompilerVisitor(self)
316 class SeparateErasureCompilerVisitor
317 super SeparateCompilerVisitor
319 redef fun compile_callsite
(callsite
, arguments
)
322 if callsite
.erasure_cast
and not self.compiler
.as(SeparateErasureCompiler).modelbuilder
.toolcontext
.opt_no_check_erasure_cast
.value
then
324 var mtype
= callsite
.msignature
.return_mtype
326 self.add
("/* Erasure cast for return {res} isa {mtype} */")
327 var cond
= self.type_test
(res
, mtype
)
328 self.add
("if (!{cond}) \{")
329 #var x = self.class_name_string(res)
330 #var y = self.class_name_string(arguments.first)
331 #self.add("fprintf(stderr, \"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
332 self.add_abort
("Cast failed")
338 redef fun init_instance
(mtype
)
340 return self.new_expr
("NEW_{mtype.mclass.c_name}()", mtype
)
343 redef fun type_test
(value
, mtype
)
345 self.add
("/* type test for {value.inspect} isa {mtype} */")
347 var res
= self.new_var
(bool_type
)
349 var cltype
= self.get_name
("cltype")
350 self.add_decl
("int {cltype};")
351 var idtype
= self.get_name
("idtype")
352 self.add_decl
("int {idtype};")
353 var is_nullable
= self.get_name
("is_nullable")
354 self.add_decl
("short int {is_nullable};")
355 var is_null
= self.get_name
("is_null")
356 self.add_decl
("short int {is_null};")
359 if mtype
isa MNullableType then
362 self.add
("{is_nullable} = 1;")
364 if mtype
isa MParameterType then
365 # Here we get the bound of the the formal type (eh, erasure...)
366 mtype
= mtype
.resolve_for
(self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.mmodule
, false)
367 if mtype
isa MNullableType then
370 self.add
("{is_nullable} = 1;")
373 if mtype
isa MVirtualType then
374 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
375 #mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
376 #if mtype isa MNullableType then
377 # mtype = mtype.mtype
382 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
383 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
389 if value
.mtype
.ctype
== "val*" then
390 class_ptr
= "{value}->class->"
391 self.add
("{is_null} = {value} == NULL;")
393 var mclass
= value
.mtype
.as(MClassType).mclass
394 class_ptr
= "class_{mclass.c_name}."
395 self.add
("{is_null} = 0;")
398 if mtype
isa MClassType then
399 self.add
("{cltype} = class_{mtype.mclass.c_name}.color;")
400 self.add
("{idtype} = class_{mtype.mclass.c_name}.id;")
401 if maybe_null
== 0 then
402 self.add
("{is_nullable} = 0;")
404 else if mtype
isa MVirtualType then
405 var recv
= self.frame
.arguments
.first
407 if recv
.mtype
.ctype
== "val*" then
408 recv_ptr
= "{recv}->class->"
410 var mclass
= recv
.mtype
.as(MClassType).mclass
411 recv_ptr
= "class_{mclass.c_name}."
413 var entry
= self.get_name
("entry")
414 self.add
("struct vts_entry {entry};")
415 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
416 self.add
("{entry} = {recv_ptr}vts_table->vts[HASH({recv_ptr}vts_table->mask, {mtype.mproperty.const_color})];")
418 self.add
("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
420 self.add
("{cltype} = {entry}.class->color;")
421 self.add
("{idtype} = {entry}.class->id;")
422 if maybe_null
== 0 then
423 self.add
("{is_nullable} = {entry}.is_nullable;")
426 self.debug
("type_test({value.inspect}, {mtype})")
430 # check color is in table
431 self.add
("if({is_null}) \{")
432 self.add
("{res} = {is_nullable};")
433 self.add
("\} else \{")
434 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
435 self.add
("{cltype} = HASH({class_ptr}color, {idtype});")
437 self.add
("if({cltype} >= {class_ptr}type_table->size) \{")
438 self.add
("{res} = 0;")
439 self.add
("\} else \{")
440 self.add
("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
447 redef fun class_name_string
(value
)
449 var res
= self.get_name
("var_class_name")
450 self.add_decl
("const char* {res};")
451 if value
.mtype
.ctype
== "val*" then
452 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->class->name;"
454 self.add
"{res} = class_{value.mtype.c_name}.name;"
459 redef fun array_instance
(array
, elttype
)
461 var nclass
= self.get_class
("NativeArray")
462 elttype
= self.anchor
(elttype
)
463 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
464 var res
= self.init_instance
(arraytype
)
465 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
466 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
468 self.add
("{nat} = NEW_{nclass.c_name}({array.length});")
469 for i
in [0..array
.length
[ do
470 var r
= self.autobox
(array
[i
], self.object_type
)
471 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
473 var length
= self.int_instance
(array
.length
)
474 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
475 self.check_init_instance
(res
, arraytype
)
480 redef fun calloc_array
(ret_type
, arguments
)
482 var ret
= ret_type
.as(MClassType)
483 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type
))