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
16 module separate_compiler
19 import global_compiler
# TODO better separation of concerns
22 redef class ToolContext
24 var opt_separate
: OptionBool = new OptionBool("Use separate compilation", "--separate")
27 var opt_no_inline_intern
: OptionBool = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
29 # --inline-coloring-numbers
30 var opt_inline_coloring_numbers
: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
32 # --use-naive-coloring
33 var opt_bm_typing
: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
35 # --use-mod-perfect-hashing
36 var opt_phmod_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with mod operator)", "--phmod-typing")
38 # --use-and-perfect-hashing
39 var opt_phand_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with and operator)", "--phand-typing")
41 # --generic-resolution-tree
42 var opt_generic_tree
: OptionBool = new OptionBool("Use tree representation for live generic types instead of flattened representation", "--generic-resolution-tree")
47 self.option_context
.add_option
(self.opt_separate
)
48 self.option_context
.add_option
(self.opt_no_inline_intern
)
49 self.option_context
.add_option
(self.opt_inline_coloring_numbers
)
50 self.option_context
.add_option
(self.opt_bm_typing
)
51 self.option_context
.add_option
(self.opt_phmod_typing
)
52 self.option_context
.add_option
(self.opt_phand_typing
)
53 self.option_context
.add_option
(self.opt_generic_tree
)
57 redef class ModelBuilder
58 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
61 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
63 var compiler
= new SeparateCompiler(mainmodule
, runtime_type_analysis
, self)
65 # compile class structures
66 for m
in mainmodule
.in_importation
.greaters
do
67 for mclass
in m
.intro_mclasses
do
68 compiler
.compile_class_to_c
(mclass
)
72 # The main function of the C
73 compiler
.compile_main_function
76 for m
in mainmodule
.in_importation
.greaters
do
77 compiler
.compile_module_to_c
(m
)
80 # compile live & cast type structures
81 var mtypes
= compiler
.do_type_coloring
83 compiler
.compile_type_to_c
(t
)
86 if self.toolcontext
.opt_generic_tree
.value
then
87 # compile live generic types selection structures
88 for mclass
in model
.mclasses
do
89 compiler
.compile_live_gentype_to_c
(mclass
)
93 write_and_make
(compiler
)
97 # Singleton that store the knowledge about the separate compilation process
98 class SeparateCompiler
99 super GlobalCompiler # TODO better separation of concerns
101 private var undead_types
: Set[MType] = new HashSet[MType]
102 private var partial_types
: Set[MType] = new HashSet[MType]
103 protected var typeids
: HashMap[MType, Int] protected writable = new HashMap[MType, Int]
105 private var type_colors
: Map[MType, Int] = typeids
106 private var type_tables
: nullable Map[MType, Array[nullable MType]] = null
108 private var livetypes_colors
: nullable Map[MType, Int]
109 private var livetypes_tables
: nullable Map[MClass, Array[nullable Object]]
110 private var livetypes_tables_sizes
: nullable Map[MClass, Array[Int]]
111 private var live_unanchored_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
113 private var unanchored_types_colors
: nullable Map[MType, Int]
114 private var unanchored_types_tables
: nullable Map[MClassType, Array[nullable MType]]
115 private var unanchored_types_masks
: nullable Map[MClassType, Int]
117 protected var class_coloring
: ClassColoring
119 protected var method_colors
: Map[MMethod, Int]
120 protected var method_tables
: Map[MClass, Array[nullable MMethodDef]]
122 protected var attr_colors
: Map[MAttribute, Int]
123 protected var attr_tables
: Map[MClass, Array[nullable MAttributeDef]]
125 protected var vt_colors
: Map[MVirtualTypeProp, Int]
126 protected var vt_tables
: Map[MClass, Array[nullable MVirtualTypeDef]]
127 protected var vt_masks
: nullable Map[MClass, Int]
129 private var ft_colors
: nullable Map[MParameterType, Int]
130 private var ft_tables
: nullable Map[MClass, Array[nullable MParameterType]]
131 private var ft_masks
: nullable Map[MClass, Int]
133 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
134 self.do_property_coloring
135 self.compile_box_kinds
138 redef fun compile_header_structs
do
139 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
140 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
141 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
143 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
144 # With generic_tree, only ft and vt resolution is stored in the type
145 self.header
.add_decl
("struct type \{ int id; const char *name; int color; short int is_nullable; int livecolor; struct types *vts_table; struct types *fts_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
147 # With unanchored_table, all live type resolution are stored in a big table: unanchored_table
148 self.header
.add_decl
("struct type \{ int id; const char *name; int color; short int is_nullable; struct types *unanchored_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
151 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
152 self.header
.add_decl
("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
154 self.header
.add_decl
("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
158 self.header
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
161 redef fun compile_class_names
do
162 abort # There is no class name compilation since the name is stored in the type structure
165 fun compile_box_kinds
167 # Collect all bas box class
168 # FIXME: this is not completely fine with a separate compilation scheme
169 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
170 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
171 if classes
== null then continue
172 assert classes
.length
== 1 else print classes
.join
(", ")
173 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
177 var box_kinds
= new HashMap[MClass, Int]
179 fun box_kind_of
(mclass
: MClass): Int
181 if mclass
.mclass_type
.ctype
== "val*" then
183 else if mclass
.kind
== extern_kind
then
184 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
186 return self.box_kinds
[mclass
]
191 fun compile_color_consts
(colors
: Map[Object, Int]) do
192 for m
, c
in colors
do
193 if m
isa MProperty then
194 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
195 self.header
.add_decl
("#define {m.const_color} {c}")
197 self.header
.add_decl
("extern const int {m.const_color};")
198 self.header
.add
("const int {m.const_color} = {c};")
200 else if m
isa MType then
201 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
202 self.header
.add_decl
("#define {m.const_color} {c}")
204 self.header
.add_decl
("extern const int {m.const_color};")
205 self.header
.add
("const int {m.const_color} = {c};")
211 # colorize classe properties
212 fun do_property_coloring
do
215 self.class_coloring
= new ClassColoring(mainmodule
)
216 class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
219 var method_coloring
= new MethodColoring(self.class_coloring
)
220 self.method_colors
= method_coloring
.colorize
221 self.method_tables
= method_coloring
.build_property_tables
222 self.compile_color_consts
(self.method_colors
)
224 # attributes coloration
225 var attribute_coloring
= new AttributeColoring(self.class_coloring
)
226 self.attr_colors
= attribute_coloring
.colorize
227 self.attr_tables
= attribute_coloring
.build_property_tables
228 self.compile_color_consts
(self.attr_colors
)
230 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
231 self.class_coloring
= new NaiveClassColoring(mainmodule
)
232 self.class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
236 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
237 var vt_coloring
= new NaiveVTColoring(self.class_coloring
)
238 self.vt_colors
= vt_coloring
.colorize
239 self.vt_tables
= vt_coloring
.build_property_tables
240 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
241 var vt_coloring
= new VTModPerfectHashing(self.class_coloring
)
242 self.vt_colors
= vt_coloring
.colorize
243 self.vt_masks
= vt_coloring
.compute_masks
244 self.vt_tables
= vt_coloring
.build_property_tables
245 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
246 var vt_coloring
= new VTAndPerfectHashing(self.class_coloring
)
247 self.vt_colors
= vt_coloring
.colorize
248 self.vt_masks
= vt_coloring
.compute_masks
249 self.vt_tables
= vt_coloring
.build_property_tables
251 var vt_coloring
= new VTColoring(self.class_coloring
)
252 self.vt_colors
= vt_coloring
.colorize
253 self.vt_tables
= vt_coloring
.build_property_tables
255 self.compile_color_consts
(self.vt_colors
)
258 # colorize live types of the program
259 private fun do_type_coloring
: Set[MType] do
260 var mtypes
= new HashSet[MType]
261 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
262 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
263 mtypes
.add_all
(self.undead_types
)
264 for c
in self.box_kinds
.keys
do
265 mtypes
.add
(c
.mclass_type
)
268 for mtype
in mtypes
do
269 retieve_live_partial_types
(mtype
)
271 mtypes
.add_all
(self.partial_types
)
274 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
275 var sorted_mtypes
= new OrderedSet[MType].from
(mtypes
)
276 sorted_mtypes
.linearize
(new ReverseTypeSorter(self.mainmodule
))
277 for mtype
in sorted_mtypes
do
278 self.typeids
[mtype
] = self.typeids
.length
+ 1
281 for mtype
in mtypes
do
282 self.typeids
[mtype
] = self.typeids
.length
286 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
287 # fts coloration for non-erased compilation
288 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
289 var ft_coloring
= new NaiveFTColoring(self.class_coloring
)
290 self.ft_colors
= ft_coloring
.colorize
291 self.ft_tables
= ft_coloring
.build_ft_tables
292 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
293 var ft_coloring
= new FTModPerfectHashing(self.class_coloring
)
294 self.ft_colors
= ft_coloring
.colorize
295 self.ft_masks
= ft_coloring
.compute_masks
296 self.ft_tables
= ft_coloring
.build_ft_tables
297 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
298 var ft_coloring
= new FTAndPerfectHashing(self.class_coloring
)
299 self.ft_colors
= ft_coloring
.colorize
300 self.ft_masks
= ft_coloring
.compute_masks
301 self.ft_tables
= ft_coloring
.build_ft_tables
303 var ft_coloring
= new FTColoring(self.class_coloring
)
304 self.ft_colors
= ft_coloring
.colorize
305 self.ft_tables
= ft_coloring
.build_ft_tables
307 self.compile_color_consts
(self.ft_colors
.as(not null))
309 # colorize live entries
311 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
312 entries_coloring
= new NaiveLiveEntryColoring
314 entries_coloring
= new LiveEntryColoring
316 self.livetypes_colors
= entries_coloring
.colorize
(mtypes
)
317 self.livetypes_tables
= entries_coloring
.build_livetype_tables
(mtypes
)
318 self.livetypes_tables_sizes
= entries_coloring
.livetypes_tables_sizes
320 # VT and FT are stored with other unresolved types in the big unanchored_tables
321 self.compile_unanchored_tables
(mtypes
)
325 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
326 var type_coloring
= new NaiveTypeColoring(self.mainmodule
, mtypes
)
327 self.type_colors
= type_coloring
.colorize
(mtypes
)
328 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
329 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
330 var type_coloring
= new TypeModPerfectHashing(self.mainmodule
, mtypes
)
331 self.type_colors
= type_coloring
.compute_masks
(mtypes
, typeids
)
332 self.type_tables
= type_coloring
.hash_type_tables
(mtypes
, typeids
, type_colors
)
333 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
334 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
335 var type_coloring
= new TypeAndPerfectHashing(self.mainmodule
, mtypes
)
336 self.type_colors
= type_coloring
.compute_masks
(mtypes
, typeids
)
337 self.type_tables
= type_coloring
.hash_type_tables
(mtypes
, typeids
, type_colors
)
338 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
340 var type_coloring
= new TypeColoring(self.mainmodule
, mtypes
)
341 self.type_colors
= type_coloring
.colorize
(mtypes
)
342 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
349 protected fun compile_unanchored_tables
(mtypes
: Set[MType]) do
350 # Unanchored_tables is used to perform a type resolution at runtime in O(1)
352 # During the visit of the body of classes, live_unanchored_types are collected
354 # Collect all live_unanchored_types (visited in the body of classes)
356 # Determinate fo each livetype what are its possible requested anchored types
357 var mtype2unanchored
= new HashMap[MClassType, Set[MType]]
358 for mtype
in self.runtime_type_analysis
.live_types
do
359 var set
= new HashSet[MType]
360 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
361 if self.live_unanchored_types
.has_key
(cd
) then
362 set
.add_all
(self.live_unanchored_types
[cd
])
365 mtype2unanchored
[mtype
] = set
368 # Compute the table layout with the prefered method
369 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
370 var unanchored_type_coloring
= new NaiveUnanchoredTypeColoring
371 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2unanchored
)
372 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2unanchored
)
373 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
374 var unanchored_type_coloring
= new UnanchoredTypeModPerfectHashing
375 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2unanchored
)
376 self.unanchored_types_masks
= unanchored_type_coloring
.compute_masks
(mtype2unanchored
)
377 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2unanchored
)
378 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
379 var unanchored_type_coloring
= new UnanchoredTypeAndPerfectHashing
380 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2unanchored
)
381 self.unanchored_types_masks
= unanchored_type_coloring
.compute_masks
(mtype2unanchored
)
382 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2unanchored
)
384 var unanchored_type_coloring
= new UnanchoredTypeColoring
385 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2unanchored
)
386 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2unanchored
)
389 # Compile a C constant for each collected unanchored type.
390 # Either to a color, or to -1 if the unanchored type is dead (no live receiver can require it)
391 var all_unanchored
= new HashSet[MType]
392 for t
in self.live_unanchored_types
.values
do
393 all_unanchored
.add_all
(t
)
395 var all_unanchored_types_colors
= new HashMap[MType, Int]
396 for t
in all_unanchored
do
397 if unanchored_types_colors
.has_key
(t
) then
398 all_unanchored_types_colors
[t
] = unanchored_types_colors
[t
]
400 all_unanchored_types_colors
[t
] = -1
403 self.compile_color_consts
(all_unanchored_types_colors
)
406 #for k, v in unanchored_types_tables.as(not null) do
407 # print "{k}: {v.join(", ")}"
412 fun retieve_live_partial_types
(mtype
: MType) do
413 # add formal types arguments to mtypes
414 if mtype
isa MGenericType then
415 for ft
in mtype
.arguments
do
416 if ft
.need_anchor
then
417 print
("Why do we need anchor here ?")
420 self.partial_types
.add
(ft
)
421 retieve_live_partial_types
(ft
)
424 var mclass_type
: MClassType
425 if mtype
isa MNullableType then
426 mclass_type
= mtype
.mtype
.as(MClassType)
428 mclass_type
= mtype
.as(MClassType)
431 # add virtual types to mtypes
432 for vt
in self.vt_tables
[mclass_type
.mclass
] do
434 var anchored
= vt
.bound
.anchor_to
(self.mainmodule
, mclass_type
)
435 self.partial_types
.add
(anchored
)
440 # declare live generic types tables selection
441 private fun compile_live_gentype_to_c
(mclass
: MClass) do
442 if mclass
.arity
> 0 then
443 if self.livetypes_tables
.has_key
(mclass
) then
444 var table
= self.livetypes_tables
[mclass
]
445 var sign
= self.livetypes_tables_sizes
[mclass
]
446 var table_buffer
= new Buffer.from
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}] = \{\n")
447 compile_livetype_table
(table
, table_buffer
, 1, mclass
.arity
)
448 table_buffer
.append
("\};")
450 var v
= new SeparateCompilerVisitor(self)
451 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
452 v
.add_decl
(table_buffer
.to_s
)
454 var sign
= new Array[Int].filled_with
(0, mclass
.arity
)
455 var v
= new SeparateCompilerVisitor(self)
456 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
457 v
.add_decl
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
462 private fun compile_livetype_table
(table
: Array[nullable Object], buffer
: Buffer, depth
: Int, max
: Int) do
466 buffer
.append
("NULL,\n")
468 buffer
.append
("\{\},\n")
470 else if obj
isa MClassType then
471 buffer
.append
("(struct type*) &type_{obj.c_name}, /* {obj} */\n")
472 else if obj
isa Array[nullable Object] then
473 buffer
.append
("\{\n")
474 compile_livetype_table
(obj
, buffer
, depth
+ 1, max
)
475 buffer
.append
("\},\n")
480 # Separately compile all the method definitions of the module
481 fun compile_module_to_c
(mmodule
: MModule)
483 var old_module
= self.mainmodule
484 self.mainmodule
= mmodule
485 for cd
in mmodule
.mclassdefs
do
486 for pd
in cd
.mpropdefs
do
487 if not pd
isa MMethodDef then continue
488 #print "compile {pd} @ {cd} @ {mmodule}"
489 var r
= new SeparateRuntimeFunction(pd
)
491 if true or cd
.bound_mtype
.ctype
!= "val*" then
492 var r2
= new VirtualRuntimeFunction(pd
)
493 r2
.compile_to_c
(self)
497 self.mainmodule
= old_module
500 # Globaly compile the type structure of a live type
501 fun compile_type_to_c
(mtype
: MType)
503 var c_name
= mtype
.c_name
504 var v
= new SeparateCompilerVisitor(self)
505 v
.add_decl
("/* runtime type {mtype} */")
507 # extern const struct type_X
508 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
509 self.header
.add_decl
("struct type_{c_name} \{")
510 self.header
.add_decl
("int id;")
511 self.header
.add_decl
("const char *name;")
512 self.header
.add_decl
("int color;")
513 self.header
.add_decl
("short int is_nullable;")
514 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
515 self.header
.add_decl
("int livecolor;")
516 self.header
.add_decl
("const struct vts_table_{c_name} *vts_table;")
517 self.header
.add_decl
("const struct fts_table_{c_name} *fts_table;")
519 self.header
.add_decl
("const struct types *unanchored_table;")
521 self.header
.add_decl
("int table_size;")
522 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
523 self.header
.add_decl
("\};")
525 # const struct type_X
526 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
527 v
.add_decl
("{self.typeids[mtype]},")
528 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
529 v
.add_decl
("{self.type_colors[mtype]},")
530 if mtype
isa MNullableType then
535 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
536 v
.add_decl
("{self.livetypes_colors[mtype]},")
537 if compile_type_vts_table
(mtype
) then
538 v
.add_decl
("&vts_table_{c_name},")
542 if compile_type_fts_table
(mtype
) then
543 v
.add_decl
("&fts_table_{c_name},")
548 if compile_type_unanchored_table
(mtype
) then
549 v
.add_decl
("(struct types*) &unanchored_table_{c_name},")
554 v
.add_decl
("{self.type_tables[mtype].length},")
556 for stype
in self.type_tables
[mtype
] do
557 if stype
== null then
558 v
.add_decl
("-1, /* empty */")
560 v
.add_decl
("{self.typeids[stype]}, /* {stype} */")
567 protected fun compile_type_fts_table
(mtype
: MType): Bool do
569 var mclass_type
: MClassType
570 if mtype
isa MNullableType then
571 mclass_type
= mtype
.mtype
.as(MClassType)
573 mclass_type
= mtype
.as(MClassType)
575 if self.ft_tables
[mclass_type
.mclass
].is_empty
then return false
577 # extern const struct fst_table_X fst_table_X
578 self.header
.add_decl
("extern const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name};")
579 self.header
.add_decl
("struct fts_table_{mtype.c_name} \{")
580 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
581 self.header
.add_decl
("int mask;")
583 self.header
.add_decl
("struct type *types[{self.ft_tables[mclass_type.mclass].length}];")
584 self.header
.add_decl
("\};")
586 # const struct fts_table_X fts_table_X
588 v
.add_decl
("const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name} = \{")
589 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
590 v
.add_decl
("{self.ft_masks[mclass_type.mclass]},")
593 for ft
in self.ft_tables
[mclass_type
.mclass
] do
595 v
.add_decl
("NULL, /* empty */")
598 if ft
.mclass
== mclass_type
.mclass
then
599 ntype
= mclass_type
.arguments
[ft
.rank
]
601 ntype
= ft
.anchor_to
(self.mainmodule
, mclass_type
)
603 if self.typeids
.has_key
(ntype
) then
604 v
.add_decl
("(struct type*)&type_{ntype.c_name}, /* {ft} ({ntype}) */")
606 v
.add_decl
("NULL, /* empty ({ft} not a live type) */")
615 protected fun compile_type_vts_table
(mtype
: MType): Bool do
617 var mclass_type
: MClassType
618 if mtype
isa MNullableType then
619 mclass_type
= mtype
.mtype
.as(MClassType)
621 mclass_type
= mtype
.as(MClassType)
623 if self.vt_tables
[mclass_type
.mclass
].is_empty
then return false
625 # extern const struct vts_table_X vts_table_X
626 self.header
.add_decl
("extern const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name};")
627 self.header
.add_decl
("struct vts_table_{mtype.c_name} \{")
628 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
629 self.header
.add_decl
("int mask;")
631 self.header
.add_decl
("struct type *types[{self.vt_tables[mclass_type.mclass].length}];")
632 self.header
.add_decl
("\};")
634 # const struct vts_table_X vts_table_X
636 v
.add_decl
("const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name} = \{")
637 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
638 v
.add_decl
("{vt_masks[mclass_type.mclass]},")
642 for vt
in self.vt_tables
[mclass_type
.mclass
] do
644 v
.add_decl
("NULL, /* empty */")
647 if bound
== null then
648 #FIXME how can a bound be null here ?
649 print
"No bound found for virtual type {vt} ?"
653 if bound
isa MNullableType then
655 is_nullable
= "nullable_"
657 if bound
isa MVirtualType then
658 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
659 else if bound
isa MParameterType then
660 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
661 else if bound
isa MGenericType and bound
.need_anchor
then
662 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
663 else if bound
isa MClassType then
665 print
"NOT YET IMPLEMENTED: mtype_to_livetype with type: {bound}"
669 if self.typeids
.has_key
(bound
) then
670 v
.add_decl
("(struct type*)&type_{is_nullable}{bound.c_name}, /* {bound} */")
672 v
.add_decl
("NULL, /* dead type {bound} */")
682 fun compile_type_unanchored_table
(mtype
: MType): Bool do
684 var mclass_type
: MClassType
685 if mtype
isa MNullableType then
686 mclass_type
= mtype
.mtype
.as(MClassType)
688 mclass_type
= mtype
.as(MClassType)
690 if not self.unanchored_types_tables
.has_key
(mclass_type
) then return false
692 # extern const struct unanchored_table_X unanchored_table_X
693 self.header
.add_decl
("extern const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name};")
695 self.header
.add_decl
("struct unanchored_table_{mtype.c_name} \{")
696 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
697 self.header
.add_decl
("int mask;")
699 self.header
.add_decl
("struct type *types[{self.unanchored_types_tables[mclass_type].length}];")
700 self.header
.add_decl
("\};")
702 # const struct fts_table_X fts_table_X
704 v
.add_decl
("const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name} = \{")
705 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
706 v
.add_decl
("{self.unanchored_types_masks[mclass_type]},")
709 for t
in self.unanchored_types_tables
[mclass_type
] do
711 v
.add_decl
("NULL, /* empty */")
713 # The table stores the result of the type resolution
714 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
715 # the value stored is tv.
716 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
717 # FIXME: What typeids means here? How can a tv not be live?
718 if self.typeids
.has_key
(tv
) then
719 v
.add_decl
("(struct type*)&type_{tv.c_name}, /* {t}: {tv} */")
721 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
730 # Globally compile the table of the class mclass
731 # In a link-time optimisation compiler, tables are globally computed
732 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
733 fun compile_class_to_c
(mclass
: MClass)
735 var mtype
= mclass
.intro
.bound_mtype
736 var c_name
= mclass
.c_name
738 var vft
= self.method_tables
[mclass
]
739 var attrs
= self.attr_tables
[mclass
]
742 v
.add_decl
("/* runtime class {c_name} */")
743 var idnum
= classids
.length
744 var idname
= "ID_" + c_name
745 self.classids
[mtype
] = idname
746 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
748 self.header
.add_decl
("struct class_{c_name} \{")
749 self.header
.add_decl
("int box_kind;")
750 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
751 self.header
.add_decl
("\};")
754 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
755 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
756 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
758 for i
in [0 .. vft
.length
[ do
759 var mpropdef
= vft
[i
]
760 if mpropdef
== null then
761 v
.add_decl
("NULL, /* empty */")
763 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
764 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
766 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
773 if mtype
.ctype
!= "val*" then
774 #Build instance struct
775 self.header
.add_decl
("struct instance_{c_name} \{")
776 self.header
.add_decl
("const struct type *type;")
777 self.header
.add_decl
("const struct class *class;")
778 self.header
.add_decl
("{mtype.ctype} value;")
779 self.header
.add_decl
("\};")
781 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
783 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
784 v
.add_decl
("/* allocate {mtype} */")
785 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
786 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
787 v
.add
("res->type = (struct type*) &type_{c_name};")
788 v
.add
("res->class = (struct class*) &class_{c_name};")
789 v
.add
("res->value = value;")
790 v
.add
("return (val*)res;")
795 var is_native_array
= mclass
.name
== "NativeArray"
798 if is_native_array
then
799 sig
= "int length, struct type* type"
801 sig
= "struct type* type"
804 #Build instance struct
805 #extern const struct instance_array__NativeArray instance_array__NativeArray;
806 self.header
.add_decl
("struct instance_{c_name} \{")
807 self.header
.add_decl
("const struct type *type;")
808 self.header
.add_decl
("const struct class *class;")
809 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
810 if is_native_array
then
811 # NativeArrays are just a instance header followed by an array of values
812 self.header
.add_decl
("val* values[0];")
814 self.header
.add_decl
("\};")
817 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
818 v
.add_decl
("/* allocate {mtype} */")
819 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
820 var res
= v
.new_named_var
(mtype
, "self")
822 if is_native_array
then
823 var mtype_elt
= mtype
.arguments
.first
824 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
826 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
828 #v.add("{res} = calloc(sizeof(struct instance_{c_name}), 1);")
829 v
.add
("{res}->type = type;")
830 v
.add
("{res}->class = (struct class*) &class_{c_name};")
832 self.generate_init_attr
(v
, res
, mtype
)
833 v
.add
("return {res};")
836 generate_check_init_instance
(mtype
)
839 redef fun generate_check_init_instance
(mtype
)
841 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
843 var v
= self.new_visitor
844 var c_name
= mtype
.mclass
.c_name
845 var res
= new RuntimeVariable("self", mtype
, mtype
)
846 self.header
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype});")
847 v
.add_decl
("/* allocate {mtype} */")
848 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
849 self.generate_check_attr
(v
, res
, mtype
)
853 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
856 # The C function associated to a methoddef separately compiled
857 class SeparateRuntimeFunction
858 super AbstractRuntimeFunction
860 redef fun build_c_name
: String
862 return "{mmethoddef.c_name}"
865 redef fun to_s
do return self.mmethoddef
.to_s
867 redef fun compile_to_c
(compiler
)
869 var mmethoddef
= self.mmethoddef
871 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
872 var v
= compiler
.new_visitor
873 var selfvar
= new RuntimeVariable("self", recv
, recv
)
874 var arguments
= new Array[RuntimeVariable]
875 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
878 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
881 var comment
= new Buffer
882 var ret
= msignature
.return_mtype
884 sig
.append
("{ret.ctype} ")
885 else if mmethoddef
.mproperty
.is_new
then
887 sig
.append
("{ret.ctype} ")
891 sig
.append
(self.c_name
)
892 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
893 comment
.append
("(self: {selfvar}")
894 arguments
.add
(selfvar
)
895 for i
in [0..msignature
.arity
[ do
896 var mtype
= msignature
.mparameters
[i
].mtype
897 if i
== msignature
.vararg_rank
then
898 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
900 comment
.append
(", {mtype}")
901 sig
.append
(", {mtype.ctype} p{i}")
902 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
903 arguments
.add
(argvar
)
908 comment
.append
(": {ret}")
910 compiler
.header
.add_decl
("{sig};")
912 v
.add_decl
("/* method {self} for {comment} */")
913 v
.add_decl
("{sig} \{")
915 frame
.returnvar
= v
.new_var
(ret
)
917 frame
.returnlabel
= v
.get_name
("RET_LABEL")
919 if recv
!= arguments
.first
.mtype
then
920 #print "{self} {recv} {arguments.first}"
922 mmethoddef
.compile_inside_to_c
(v
, arguments
)
924 v
.add
("{frame.returnlabel.as(not null)}:;")
926 v
.add
("return {frame.returnvar.as(not null)};")
932 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
933 # The first parameter (the reciever) is always typed by val* in order to accept an object value
934 class VirtualRuntimeFunction
935 super AbstractRuntimeFunction
937 redef fun build_c_name
: String
939 return "VIRTUAL_{mmethoddef.c_name}"
942 redef fun to_s
do return self.mmethoddef
.to_s
944 redef fun compile_to_c
(compiler
)
946 var mmethoddef
= self.mmethoddef
948 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
949 var v
= compiler
.new_visitor
950 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
951 var arguments
= new Array[RuntimeVariable]
952 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
956 var comment
= new Buffer
958 # Because the function is virtual, the signature must match the one of the original class
959 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
960 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
961 var ret
= msignature
.return_mtype
963 sig
.append
("{ret.ctype} ")
964 else if mmethoddef
.mproperty
.is_new
then
966 sig
.append
("{ret.ctype} ")
970 sig
.append
(self.c_name
)
971 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
972 comment
.append
("(self: {selfvar}")
973 arguments
.add
(selfvar
)
974 for i
in [0..msignature
.arity
[ do
975 var mtype
= msignature
.mparameters
[i
].mtype
976 if i
== msignature
.vararg_rank
then
977 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
979 comment
.append
(", {mtype}")
980 sig
.append
(", {mtype.ctype} p{i}")
981 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
982 arguments
.add
(argvar
)
987 comment
.append
(": {ret}")
989 compiler
.header
.add_decl
("{sig};")
991 v
.add_decl
("/* method {self} for {comment} */")
992 v
.add_decl
("{sig} \{")
994 frame
.returnvar
= v
.new_var
(ret
)
996 frame
.returnlabel
= v
.get_name
("RET_LABEL")
998 if recv
!= arguments
.first
.mtype
then
999 #print "{self} {recv} {arguments.first}"
1001 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1003 v
.add
("{frame.returnlabel.as(not null)}:;")
1005 v
.add
("return {frame.returnvar.as(not null)};")
1010 redef fun call
(v
, arguments
)
1017 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
1018 class SeparateCompilerVisitor
1019 super GlobalCompilerVisitor # TODO better separation of concerns
1021 redef fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
1023 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
1024 var recv
= args
.first
1025 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
1026 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
1028 for i
in [0..msignature
.arity
[ do
1029 var t
= msignature
.mparameters
[i
].mtype
1030 if i
== msignature
.vararg_rank
then
1033 args
[i
+1] = self.autobox
(args
[i
+1], t
)
1037 # Box or unbox a value to another type iff a C type conversion is needed
1038 # ENSURE: result.mtype.ctype == mtype.ctype
1039 redef fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1041 if value
.mtype
== mtype
then
1043 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
1045 else if value
.mtype
.ctype
== "val*" then
1046 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
1047 else if mtype
.ctype
== "val*" then
1048 var valtype
= value
.mtype
.as(MClassType)
1049 var res
= self.new_var
(mtype
)
1050 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
1051 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
1052 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
1055 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
1058 # Bad things will appen!
1059 var res
= self.new_var
(mtype
)
1060 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
1061 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
1066 # Return a C expression returning the runtime type structure of the value
1067 # The point of the method is to works also with primitives types.
1068 fun type_info
(value
: RuntimeVariable): String
1070 if value
.mtype
.ctype
== "val*" then
1071 return "{value}->type"
1073 return "(&type_{value.mtype.c_name})"
1077 redef fun send
(mmethod
, arguments
)
1079 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1080 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
1083 var res
: nullable RuntimeVariable
1084 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
1085 var ret
= msignature
.return_mtype
1086 if mmethod
.is_new
then
1087 ret
= arguments
.first
.mtype
1088 res
= self.new_var
(ret
)
1089 else if ret
== null then
1092 res
= self.new_var
(ret
)
1098 var recv
= arguments
.first
1101 self.varargize
(msignature
, arguments
)
1102 for i
in [0..msignature
.arity
[ do
1103 var a
= arguments
[i
+1]
1104 var t
= msignature
.mparameters
[i
].mtype
1105 if i
== msignature
.vararg_rank
then
1106 t
= arguments
[i
+1].mcasttype
1108 s
.append
(", {t.ctype}")
1109 a
= self.autobox
(a
, t
)
1113 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1114 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1116 self.add
("if ({recv} == NULL) \{")
1117 if mmethod
.name
== "==" then
1119 var arg
= arguments
[1]
1120 if arg
.mcasttype
isa MNullableType then
1121 self.add
("{res} = ({arg} == NULL);")
1122 else if arg
.mcasttype
isa MNullType then
1123 self.add
("{res} = 1; /* is null */")
1125 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1127 else if mmethod
.name
== "!=" then
1129 var arg
= arguments
[1]
1130 if arg
.mcasttype
isa MNullableType then
1131 self.add
("{res} = ({arg} != NULL);")
1132 else if arg
.mcasttype
isa MNullType then
1133 self.add
("{res} = 0; /* is null */")
1135 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1138 self.add_abort
("Reciever is null")
1140 self.add
("\} else \{")
1144 if ret
== null then r
= "void" else r
= ret
.ctype
1145 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1148 self.add
("{res} = {call};")
1160 redef fun call
(mmethoddef
, recvtype
, arguments
)
1162 var res
: nullable RuntimeVariable
1163 var ret
= mmethoddef
.msignature
.return_mtype
1164 if mmethoddef
.mproperty
.is_new
then
1165 ret
= arguments
.first
.mtype
1166 res
= self.new_var
(ret
)
1167 else if ret
== null then
1170 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1171 res
= self.new_var
(ret
)
1174 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1175 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1176 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1177 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1178 frame
.returnlabel
= self.get_name
("RET_LABEL")
1179 frame
.returnvar
= res
1180 var old_frame
= self.frame
1182 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1183 mmethoddef
.compile_inside_to_c
(self, arguments
)
1184 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1186 self.frame
= old_frame
1191 self.adapt_signature
(mmethoddef
, arguments
)
1194 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1197 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1203 redef fun isset_attribute
(a
, recv
)
1205 self.check_recv_notnull
(recv
)
1206 var res
= self.new_var
(bool_type
)
1207 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1211 redef fun read_attribute
(a
, recv
)
1213 self.check_recv_notnull
(recv
)
1215 # What is the declared type of the attribute?
1216 var ret
= a
.intro
.static_mtype
.as(not null)
1217 var intromclassdef
= a
.intro
.mclassdef
1218 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1220 # Get the attribute or a box (ie. always a val*)
1221 var cret
= self.object_type
.as_nullable
1222 var res
= self.new_var
(cret
)
1224 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1226 # Check for Uninitialized attribute
1227 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1228 self.add
("if ({res} == NULL) \{")
1229 self.add_abort
("Uninitialized attribute {a.name}")
1233 # Return the attribute or its unboxed version
1234 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1235 return self.autobox
(res
, ret
)
1238 redef fun write_attribute
(a
, recv
, value
)
1240 self.check_recv_notnull
(recv
)
1242 # What is the declared type of the attribute?
1243 var mtype
= a
.intro
.static_mtype
.as(not null)
1244 var intromclassdef
= a
.intro
.mclassdef
1245 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1247 # Adapt the value to the declared type
1248 value
= self.autobox
(value
, mtype
)
1249 var attr
= "{recv}->attrs[{a.const_color}]"
1250 if mtype
.ctype
!= "val*" then
1251 assert mtype
isa MClassType
1252 # The attribute is primitive, thus we store it in a box
1253 # The trick is to create the box the first time then resuse the box
1254 self.add
("if ({attr} != NULL) \{")
1255 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1256 self.add
("\} else \{")
1257 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1258 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1261 # The attribute is not primitive, thus store it direclty
1262 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1266 # Build livetype structure retrieving
1267 #ENSURE: mtype.need_anchor
1268 fun retrieve_anchored_livetype
(mtype
: MGenericType, buffer
: Buffer) do
1269 assert mtype
.need_anchor
1271 var compiler
= self.compiler
.as(SeparateCompiler)
1272 for ft
in mtype
.arguments
do
1276 if ntype
isa MNullableType then
1280 var recv
= self.frame
.arguments
.first
1281 var recv_type_info
= self.type_info
(recv
)
1282 if ntype
isa MParameterType then
1283 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1284 buffer
.append
("[{recv_type_info}->fts_table->types[HASH({recv_type_info}->fts_table->mask, {ntype.const_color})]->livecolor]")
1286 buffer
.append
("[{recv_type_info}->fts_table->types[{ntype.const_color}]->livecolor]")
1288 else if ntype
isa MVirtualType then
1289 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1290 buffer
.append
("[{recv_type_info}->vts_table->types[HASH({recv_type_info}->vts_table->mask, {ntype.mproperty.const_color})]->livecolor]")
1292 buffer
.append
("[{recv_type_info}->vts_table->types[{ntype.mproperty.const_color}]->livecolor]")
1294 else if ntype
isa MGenericType and ntype
.need_anchor
then
1295 var bbuff
= new Buffer
1296 retrieve_anchored_livetype
(ntype
, bbuff
)
1297 buffer
.append
("[livetypes_{ntype.mclass.c_name}{bbuff.to_s}->livecolor]")
1298 else if ntype
isa MClassType then
1299 compiler
.undead_types
.add
(ft
)
1300 buffer
.append
("[type_{ft.c_name}.livecolor]")
1302 self.add
("printf(\"NOT YET IMPLEMENTED: init_instance
(%s
, {mtype}).\\n\
", \"{ft}\
"); exit(1);")
1307 redef fun init_instance
(mtype
)
1309 var compiler
= self.compiler
.as(SeparateCompiler)
1310 if mtype
isa MGenericType and mtype
.need_anchor
then
1311 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1312 var buff
= new Buffer
1313 retrieve_anchored_livetype
(mtype
, buff
)
1314 mtype
= self.anchor
(mtype
).as(MClassType)
1315 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
1317 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1318 var recv
= self.frame
.arguments
.first
1319 var recv_type_info
= self.type_info
(recv
)
1320 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1321 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->unanchored_table->types[HASH({recv_type_info}->unanchored_table->mask, {mtype.const_color})])", mtype
)
1323 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1327 compiler
.undead_types
.add
(mtype
)
1328 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
1331 redef fun check_init_instance
(value
, mtype
)
1333 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1334 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1338 redef fun type_test
(value
, mtype
)
1340 self.add
("/* {value.inspect} isa {mtype} */")
1341 var compiler
= self.compiler
.as(SeparateCompiler)
1343 var recv
= self.frame
.arguments
.first
1344 var recv_type_info
= self.type_info
(recv
)
1346 var res
= self.new_var
(bool_type
)
1348 var cltype
= self.get_name
("cltype")
1349 self.add_decl
("int {cltype};")
1350 var idtype
= self.get_name
("idtype")
1351 self.add_decl
("int {idtype};")
1352 var is_nullable
= self.get_name
("is_nullable")
1353 self.add_decl
("short int {is_nullable};")
1356 if ntype
isa MNullableType then
1360 if ntype
.need_anchor
then
1361 var type_struct
= self.get_name
("type_struct")
1362 self.add_decl
("struct type* {type_struct};")
1364 # For unresolved types, there is two implementations
1365 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1366 # Either with the generic_tree and the construction of a type
1367 if ntype
isa MParameterType then
1368 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1369 self.add
("{type_struct} = {recv_type_info}->fts_table->types[HASH({recv_type_info}->fts_table->mask, {ntype.const_color})];")
1371 self.add
("{type_struct} = {recv_type_info}->fts_table->types[{ntype.const_color}];")
1373 else if ntype
isa MVirtualType then
1374 var vtcolor
= ntype
.mproperty
.const_color
1375 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1376 self.add
("{type_struct} = {recv_type_info}->vts_table->types[HASH({recv_type_info}->vts_table->mask, {vtcolor})];")
1378 self.add
("{type_struct} = {recv_type_info}->vts_table->types[{vtcolor}];")
1380 else if ntype
isa MGenericType then
1381 var buff
= new Buffer
1382 retrieve_anchored_livetype
(ntype
, buff
)
1383 self.add
("{type_struct} = (struct type*)livetypes_{ntype.mclass.c_name}{buff.to_s};")
1386 # Either with unanchored_table with a direct resolution
1387 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1388 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1389 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[HASH({recv_type_info}->unanchored_table->mask, {ntype.const_color})];")
1391 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[{ntype.const_color}];")
1394 self.add
("{cltype} = {type_struct}->color;")
1395 self.add
("{idtype} = {type_struct}->id;")
1396 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1397 else if ntype
isa MClassType then
1398 compiler
.undead_types
.add
(mtype
)
1399 self.add
("{cltype} = type_{mtype.c_name}.color;")
1400 self.add
("{idtype} = type_{mtype.c_name}.id;")
1401 self.add
("{is_nullable} = type_{mtype.c_name}.is_nullable;")
1403 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1406 if mtype
isa MNullableType then
1407 self.add
("{is_nullable} = 1;")
1410 # check color is in table
1411 if self.maybe_null
(value
) then
1412 self.add
("if({value} == NULL) \{")
1413 self.add
("{res} = {is_nullable};")
1414 self.add
("\} else \{")
1416 var value_type_info
= self.type_info
(value
)
1417 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1418 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1420 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1421 self.add
("{res} = 0;")
1422 self.add
("\} else \{")
1423 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1425 if self.maybe_null
(value
) then
1432 redef fun is_same_type_test
(value1
, value2
)
1434 var res
= self.new_var
(bool_type
)
1435 # Swap values to be symetric
1436 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1441 if value1
.mtype
.ctype
!= "val*" then
1442 if value2
.mtype
== value1
.mtype
then
1443 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1444 else if value2
.mtype
.ctype
!= "val*" then
1445 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1447 var mtype1
= value1
.mtype
.as(MClassType)
1448 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1451 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1456 redef fun class_name_string
(value
)
1458 var res
= self.get_name
("var_class_name")
1459 self.add_decl
("const char* {res};")
1460 if value
.mtype
.ctype
== "val*" then
1461 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1463 self.add
"{res} = type_{value.mtype.c_name}.name;"
1468 redef fun equal_test
(value1
, value2
)
1470 var res
= self.new_var
(bool_type
)
1471 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1476 if value1
.mtype
.ctype
!= "val*" then
1477 if value2
.mtype
== value1
.mtype
then
1478 self.add
("{res} = {value1} == {value2};")
1479 else if value2
.mtype
.ctype
!= "val*" then
1480 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1482 var mtype1
= value1
.mtype
.as(MClassType)
1483 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1484 self.add
("if ({res}) \{")
1485 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1490 var maybe_null
= true
1491 var test
= new Array[String]
1492 var t1
= value1
.mcasttype
1493 if t1
isa MNullableType then
1494 test
.add
("{value1} != NULL")
1499 var t2
= value2
.mcasttype
1500 if t2
isa MNullableType then
1501 test
.add
("{value2} != NULL")
1507 var incompatible
= false
1509 if t1
.ctype
!= "val*" then
1512 # No need to compare class
1513 else if t2
.ctype
!= "val*" then
1515 else if can_be_primitive
(value2
) then
1516 test
.add
("{value1}->class == {value2}->class")
1520 else if t2
.ctype
!= "val*" then
1522 if can_be_primitive
(value1
) then
1523 test
.add
("{value1}->class == {value2}->class")
1531 if incompatible
then
1533 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1536 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1540 if primitive
!= null then
1541 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1542 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1543 test
.add
("{value1}->class == {value2}->class")
1544 var s
= new Array[String]
1545 for t
, v
in self.compiler
.as(SeparateCompiler).box_kinds
do
1546 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1548 test
.add
("({s.join(" || ")})")
1550 self.add
("{res} = {value1} == {value2};")
1553 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1557 fun can_be_primitive
(value
: RuntimeVariable): Bool
1559 var t
= value
.mcasttype
1560 if t
isa MNullableType then t
= t
.mtype
1561 if not t
isa MClassType then return false
1562 var k
= t
.mclass
.kind
1563 return k
== interface_kind
or t
.ctype
!= "val*"
1566 fun maybe_null
(value
: RuntimeVariable): Bool
1568 var t
= value
.mcasttype
1569 return t
isa MNullableType or t
isa MNullType
1572 redef fun array_instance
(array
, elttype
)
1574 var nclass
= self.get_class
("NativeArray")
1575 var arrayclass
= self.get_class
("Array")
1576 var arraytype
= arrayclass
.get_mtype
([elttype
])
1577 var res
= self.init_instance
(arraytype
)
1578 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1579 var length
= self.int_instance
(array
.length
)
1580 var nat
= native_array_instance
(elttype
, length
)
1581 for i
in [0..array
.length
[ do
1582 var r
= self.autobox
(array
[i
], self.object_type
)
1583 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1585 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1586 self.check_init_instance
(res
, arraytype
)
1591 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1593 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1594 assert mtype
isa MGenericType
1595 var compiler
= self.compiler
.as(SeparateCompiler)
1596 if mtype
.need_anchor
then
1597 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1598 var buff
= new Buffer
1599 retrieve_anchored_livetype
(mtype
, buff
)
1600 mtype
= self.anchor
(mtype
).as(MClassType)
1601 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
1603 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1604 var recv
= self.frame
.arguments
.first
1605 var recv_type_info
= self.type_info
(recv
)
1606 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1607 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->unanchored_table->types[HASH({recv_type_info}->unanchored_table->mask, {mtype.const_color})])", mtype
)
1609 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1613 compiler
.undead_types
.add
(mtype
)
1614 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype
)
1617 redef fun native_array_def
(pname
, ret_type
, arguments
)
1619 var elttype
= arguments
.first
.mtype
1620 var nclass
= self.get_class
("NativeArray")
1621 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1622 if pname
== "[]" then
1623 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1625 else if pname
== "[]=" then
1626 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1628 else if pname
== "copy_to" then
1629 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1630 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1635 redef fun calloc_array
(ret_type
, arguments
)
1637 var mclass
= self.get_class
("ArrayCapable")
1638 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1639 var res
= self.native_array_instance
(ft
, arguments
[1])
1643 fun link_unanchored_type
(mclassdef
: MClassDef, mtype
: MType) do
1644 assert mtype
.need_anchor
1645 var compiler
= self.compiler
.as(SeparateCompiler)
1646 if not compiler
.live_unanchored_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1647 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1649 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1654 # Return the name of the C structure associated to a Nit class
1655 fun c_name
: String do
1656 var res
= self.c_name_cache
1657 if res
!= null then return res
1658 res
= "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1659 self.c_name_cache
= res
1662 private var c_name_cache
: nullable String
1666 fun const_color
: String do return "COLOR_{c_name}"
1669 redef class MParameterType
1672 var res
= self.c_name_cache
1673 if res
!= null then return res
1674 res
= "{self.mclass.c_name}_FT{self.rank}"
1675 self.c_name_cache
= res
1680 redef class MVirtualType
1683 var res
= self.c_name_cache
1684 if res
!= null then return res
1685 res
= "{self.mproperty.intro.mclassdef.mclass.c_name}_VT{self.mproperty.name}"
1686 self.c_name_cache
= res
1691 redef class MNullableType
1694 var res
= self.c_name_cache
1695 if res
!= null then return res
1696 res
= "nullable_{self.mtype.c_name}"
1697 self.c_name_cache
= res
1702 redef class MProperty
1703 fun c_name
: String do
1704 var res
= self.c_name_cache
1705 if res
!= null then return res
1706 res
= "{self.intro.c_name}"
1707 self.c_name_cache
= res
1710 private var c_name_cache
: nullable String
1712 fun const_color
: String do return "COLOR_{c_name}"