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)
43 # compile class structures
44 for m
in mainmodule
.in_importation
.greaters
do
45 for mclass
in m
.intro_mclasses
do
46 compiler
.compile_class_to_c
(mclass
)
50 # The main function of the C
51 compiler
.compile_main_function
54 for m
in mainmodule
.in_importation
.greaters
do
55 compiler
.compile_module_to_c
(m
)
58 write_and_make
(compiler
)
62 class SeparateErasureCompiler
63 super SeparateCompiler
65 private var class_ids
: HashMap[MClass, Int] = new HashMap[MClass, Int]
66 private var class_colors
: Map[MClass, Int]
67 private var class_tables
: Map[MClass, Array[nullable MClass]]
69 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
70 var mclasses
= new HashSet[MClass]
71 mclasses
.add_all
(mmbuilder
.model
.mclasses
)
74 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
76 for mclass
in mclasses
do
77 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
80 var class_coloring
= new ClassModPerfectHashing(mainmodule
)
81 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
82 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
84 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
85 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
87 for mclass
in mclasses
do
88 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
91 var class_coloring
= new ClassAndPerfectHashing(mainmodule
)
92 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
93 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
95 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
98 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
99 class_coloring
= new NaiveClassColoring(mainmodule
)
101 class_coloring
= new ClassColoring(mainmodule
)
104 for mclass
in mclasses
do
105 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
107 self.class_colors
= class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
108 self.class_tables
= class_coloring
.build_type_tables
(modelbuilder
.model
.mclasses
, class_colors
)
112 redef fun compile_header_structs
do
113 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
114 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
115 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. */")
116 self.header
.add_decl
("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
117 self.header
.add_decl
("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
119 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
120 self.header
.add_decl
("struct vts_table \{ int mask; struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
122 self.header
.add_decl
("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
125 self.header
.add_decl
("typedef struct \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
128 redef fun compile_class_to_c
(mclass
: MClass)
130 var mtype
= mclass
.intro
.bound_mtype
131 var c_name
= mclass
.c_name
133 var vft
= self.method_tables
[mclass
]
134 var attrs
= self.attr_tables
[mclass
]
135 var class_table
= self.class_tables
[mclass
]
136 var v
= self.new_visitor
138 v
.add_decl
("/* runtime class {c_name} */")
139 var idnum
= classids
.length
140 var idname
= "ID_" + c_name
141 self.classids
[mtype
] = idname
142 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
144 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
145 self.header
.add_decl
("struct class_{c_name} \{")
146 self.header
.add_decl
("int id;")
147 self.header
.add_decl
("const char *name;")
148 self.header
.add_decl
("int box_kind;")
149 self.header
.add_decl
("int color;")
150 self.header
.add_decl
("const struct vts_table *vts_table;")
151 self.header
.add_decl
("struct type_table *type_table;")
152 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
153 self.header
.add_decl
("\};")
156 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
157 v
.add_decl
("{self.class_ids[mclass]},")
158 v
.add_decl
("\"{mclass.name}\
", /* class_name_string */")
159 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
160 v
.add_decl
("{self.class_colors[mclass]},")
161 if build_class_vts_table
(mclass
) then
162 v
.add_decl
("(const struct vts_table*) &vts_table_{c_name},")
166 v
.add_decl
("(struct type_table*) &type_table_{c_name},")
168 for i
in [0 .. vft
.length
[ do
169 var mpropdef
= vft
[i
]
170 if mpropdef
== null then
171 v
.add_decl
("NULL, /* empty */")
173 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
174 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
176 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
183 # Build class type table
184 self.header
.add_decl
("extern const struct type_table_{c_name} type_table_{c_name};")
185 self.header
.add_decl
("struct type_table_{c_name} \{")
186 self.header
.add_decl
("int size;")
187 self.header
.add_decl
("int table[{class_table.length}];")
188 self.header
.add_decl
("\};")
190 v
.add_decl
("const struct type_table_{c_name} type_table_{c_name} = \{")
191 v
.add_decl
("{class_table.length},")
193 for msuper
in class_table
do
194 if msuper
== null then
195 v
.add_decl
("-1, /* empty */")
197 v
.add_decl
("{self.class_ids[msuper]}, /* {msuper} */")
203 #Build instance struct
204 if mtype
.ctype
!= "val*" then
205 self.header
.add_decl
("struct instance_{c_name} \{")
206 self.header
.add_decl
("const struct class *class;")
207 self.header
.add_decl
("{mtype.ctype} value;")
208 self.header
.add_decl
("\};")
210 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
211 v
.add_decl
("/* allocate {mtype} */")
212 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
213 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
214 v
.add
("res->class = (struct class*) &class_{c_name};")
215 v
.add
("res->value = value;")
216 v
.add
("return (val*)res;")
221 var is_native_array
= mclass
.name
== "NativeArray"
224 if is_native_array
then
230 #Build instance struct
231 #extern const struct instance_array__NativeArray instance_array__NativeArray;
232 self.header
.add_decl
("struct instance_{c_name} \{")
233 self.header
.add_decl
("const struct class *class;")
234 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
235 if is_native_array
then
236 # NativeArrays are just a instance header followed by an array of values
237 self.header
.add_decl
("val* values[0];")
239 self.header
.add_decl
("\};")
242 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
243 v
.add_decl
("/* allocate {mtype} */")
244 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
245 var res
= v
.new_named_var
(mtype
, "self")
247 if is_native_array
then
248 var mtype_elt
= mtype
.arguments
.first
249 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
251 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
253 v
.add
("{res}->class = (struct class*) &class_{c_name};")
255 self.generate_init_attr
(v
, res
, mtype
)
256 v
.add
("return {res};")
259 generate_check_init_instance
(mtype
)
262 private fun build_class_vts_table
(mclass
: MClass): Bool do
263 if self.vt_tables
[mclass
].is_empty
then return false
265 self.header
.add_decl
("extern const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name};")
266 self.header
.add_decl
("struct vts_table_{mclass.c_name} \{")
267 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
268 self.header
.add_decl
("int mask;")
270 self.header
.add_decl
("struct vts_entry vts[{self.vt_tables[mclass].length}];")
271 self.header
.add_decl
("\};")
274 v
.add_decl
("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
275 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
276 v
.add_decl
("{vt_masks[mclass]},")
280 for vt
in self.vt_tables
[mclass
] do
282 v
.add_decl
("\{-1, NULL\}, /* empty */")
285 var bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, vt
.bound
)
286 while bound
isa MNullableType do
287 bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, bound
.mtype
)
290 v
.add_decl
("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
298 private fun retrieve_vt_bound
(anchor
: MClassType, mtype
: nullable MType): MType do
299 if mtype
== null then
300 print
"NOT YET IMPLEMENTED: retrieve_vt_bound on null"
303 if mtype
isa MVirtualType then
304 return mtype
.anchor_to
(mainmodule
, anchor
)
305 else if mtype
isa MParameterType then
306 return mtype
.anchor_to
(mainmodule
, anchor
)
312 redef fun new_visitor
do return new SeparateErasureCompilerVisitor(self)
315 class SeparateErasureCompilerVisitor
316 super SeparateCompilerVisitor
318 redef fun compile_callsite
(callsite
, arguments
)
321 if callsite
.erasure_cast
and not self.compiler
.as(SeparateErasureCompiler).modelbuilder
.toolcontext
.opt_no_check_erasure_cast
.value
then
323 var mtype
= callsite
.msignature
.return_mtype
325 self.add
("/* Erasure cast for return {res} isa {mtype} */")
326 var cond
= self.type_test
(res
, mtype
)
327 self.add
("if (!{cond}) \{")
328 #var x = self.class_name_string(res)
329 #var y = self.class_name_string(arguments.first)
330 #self.add("fprintf(stderr, \"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
331 self.add_abort
("Cast failed")
337 redef fun init_instance
(mtype
)
339 return self.new_expr
("NEW_{mtype.mclass.c_name}()", mtype
)
342 redef fun type_test
(value
, mtype
)
344 self.add
("/* type test for {value.inspect} isa {mtype} */")
346 var res
= self.new_var
(bool_type
)
348 var cltype
= self.get_name
("cltype")
349 self.add_decl
("int {cltype};")
350 var idtype
= self.get_name
("idtype")
351 self.add_decl
("int {idtype};")
352 var is_nullable
= self.get_name
("is_nullable")
353 self.add_decl
("short int {is_nullable};")
354 var is_null
= self.get_name
("is_null")
355 self.add_decl
("short int {is_null};")
358 if mtype
isa MNullableType then
361 self.add
("{is_nullable} = 1;")
363 if mtype
isa MParameterType then
364 # Here we get the bound of the the formal type (eh, erasure...)
365 mtype
= mtype
.resolve_for
(self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.mmodule
, false)
366 if mtype
isa MNullableType then
369 self.add
("{is_nullable} = 1;")
372 if mtype
isa MVirtualType then
373 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
374 #mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
375 #if mtype isa MNullableType then
376 # mtype = mtype.mtype
381 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
382 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
388 if value
.mtype
.ctype
== "val*" then
389 class_ptr
= "{value}->class->"
390 self.add
("{is_null} = {value} == NULL;")
392 var mclass
= value
.mtype
.as(MClassType).mclass
393 class_ptr
= "class_{mclass.c_name}."
394 self.add
("{is_null} = 0;")
397 if mtype
isa MClassType then
398 self.add
("{cltype} = class_{mtype.mclass.c_name}.color;")
399 self.add
("{idtype} = class_{mtype.mclass.c_name}.id;")
400 if maybe_null
== 0 then
401 self.add
("{is_nullable} = 0;")
403 else if mtype
isa MVirtualType then
404 var recv
= self.frame
.arguments
.first
406 if recv
.mtype
.ctype
== "val*" then
407 recv_ptr
= "{recv}->class->"
409 var mclass
= recv
.mtype
.as(MClassType).mclass
410 recv_ptr
= "class_{mclass.c_name}."
412 var entry
= self.get_name
("entry")
413 self.add
("struct vts_entry {entry};")
414 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
415 self.add
("{entry} = {recv_ptr}vts_table->vts[HASH({recv_ptr}vts_table->mask, {mtype.mproperty.const_color})];")
417 self.add
("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
419 self.add
("{cltype} = {entry}.class->color;")
420 self.add
("{idtype} = {entry}.class->id;")
421 if maybe_null
== 0 then
422 self.add
("{is_nullable} = {entry}.is_nullable;")
425 self.debug
("type_test({value.inspect}, {mtype})")
429 # check color is in table
430 self.add
("if({is_null}) \{")
431 self.add
("{res} = {is_nullable};")
432 self.add
("\} else \{")
433 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
434 self.add
("{cltype} = HASH({class_ptr}color, {idtype});")
436 self.add
("if({cltype} >= {class_ptr}type_table->size) \{")
437 self.add
("{res} = 0;")
438 self.add
("\} else \{")
439 self.add
("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
446 redef fun class_name_string
(value
)
448 var res
= self.get_name
("var_class_name")
449 self.add_decl
("const char* {res};")
450 if value
.mtype
.ctype
== "val*" then
451 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->class->name;"
453 self.add
"{res} = class_{value.mtype.c_name}.name;"
458 redef fun array_instance
(array
, elttype
)
460 var nclass
= self.get_class
("NativeArray")
461 elttype
= self.anchor
(elttype
)
462 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
463 var res
= self.init_instance
(arraytype
)
464 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
465 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
467 self.add
("{nat} = NEW_{nclass.c_name}({array.length});")
468 for i
in [0..array
.length
[ do
469 var r
= self.autobox
(array
[i
], self.object_type
)
470 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
472 var length
= self.int_instance
(array
.length
)
473 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
474 self.check_init_instance
(res
, arraytype
)
479 redef fun calloc_array
(ret_type
, arguments
)
481 var ret
= ret_type
.as(MClassType)
482 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type
))