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[MClassType, Int]
114 private var unanchored_types_tables
: nullable Map[MClassType, Array[nullable MClassType]]
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 self.header
.add_decl
("struct type \{ int id; 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. */")
146 self.header
.add_decl
("struct type \{ int id; int color; short int is_nullable; struct types *unanchored_table; struct types *vts_table; struct types *fts_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
149 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
150 self.header
.add_decl
("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
152 self.header
.add_decl
("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
156 self.header
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
159 redef fun compile_class_names
do
160 # Build type names table
161 var type_array
= new Array[nullable MType]
162 for t
, id
in typeids
do
163 if id
>= type_array
.length
then
164 for i
in [type_array
.length
..id
[ do
171 var v
= self.new_visitor
172 self.header
.add_decl
("extern const char const * class_names[];")
173 v
.add
("const char const * class_names[] = \{")
174 for t
in type_array
do
184 fun compile_box_kinds
186 # Collect all bas box class
187 # FIXME: this is not completely fine with a separate compilation scheme
188 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
189 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
190 if classes
== null then continue
191 assert classes
.length
== 1 else print classes
.join
(", ")
192 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
196 var box_kinds
= new HashMap[MClass, Int]
198 fun box_kind_of
(mclass
: MClass): Int
200 if mclass
.mclass_type
.ctype
== "val*" then
202 else if mclass
.kind
== extern_kind
then
203 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
205 return self.box_kinds
[mclass
]
210 fun compile_color_consts
(colors
: Map[Object, Int]) do
211 for m
, c
in colors
do
212 if m
isa MProperty then
213 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
214 self.header
.add_decl
("#define {m.const_color} {c}")
216 self.header
.add_decl
("extern const int {m.const_color};")
217 self.header
.add
("const int {m.const_color} = {c};")
219 else if m
isa MType then
220 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
221 self.header
.add_decl
("#define {m.const_color} {c}")
223 self.header
.add_decl
("extern const int {m.const_color};")
224 self.header
.add
("const int {m.const_color} = {c};")
230 # colorize classe properties
231 fun do_property_coloring
do
234 self.class_coloring
= new ClassColoring(mainmodule
)
235 class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
238 var method_coloring
= new MethodColoring(self.class_coloring
)
239 self.method_colors
= method_coloring
.colorize
240 self.method_tables
= method_coloring
.build_property_tables
241 self.compile_color_consts
(self.method_colors
)
243 # attributes coloration
244 var attribute_coloring
= new AttributeColoring(self.class_coloring
)
245 self.attr_colors
= attribute_coloring
.colorize
246 self.attr_tables
= attribute_coloring
.build_property_tables
247 self.compile_color_consts
(self.attr_colors
)
249 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
250 self.class_coloring
= new NaiveClassColoring(mainmodule
)
251 self.class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
255 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
256 var vt_coloring
= new NaiveVTColoring(self.class_coloring
)
257 self.vt_colors
= vt_coloring
.colorize
258 self.vt_tables
= vt_coloring
.build_property_tables
259 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
260 var vt_coloring
= new VTModPerfectHashing(self.class_coloring
)
261 self.vt_colors
= vt_coloring
.colorize
262 self.vt_masks
= vt_coloring
.compute_masks
263 self.vt_tables
= vt_coloring
.build_property_tables
264 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
265 var vt_coloring
= new VTAndPerfectHashing(self.class_coloring
)
266 self.vt_colors
= vt_coloring
.colorize
267 self.vt_masks
= vt_coloring
.compute_masks
268 self.vt_tables
= vt_coloring
.build_property_tables
270 var vt_coloring
= new VTColoring(self.class_coloring
)
271 self.vt_colors
= vt_coloring
.colorize
272 self.vt_tables
= vt_coloring
.build_property_tables
274 self.compile_color_consts
(self.vt_colors
)
277 # colorize live types of the program
278 private fun do_type_coloring
: Set[MType] do
279 var mtypes
= new HashSet[MType]
280 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
281 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
282 mtypes
.add_all
(self.undead_types
)
284 for mtype
in mtypes
do
285 retieve_live_partial_types
(mtype
)
287 mtypes
.add_all
(self.partial_types
)
290 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
291 var sorted_mtypes
= new OrderedSet[MType].from
(mtypes
)
292 sorted_mtypes
.linearize
(new ReverseTypeSorter(self.mainmodule
))
293 for mtype
in sorted_mtypes
do
294 self.typeids
[mtype
] = self.typeids
.length
+ 1
297 for mtype
in mtypes
do
298 self.typeids
[mtype
] = self.typeids
.length
302 # fts coloration for non-erased compilation
303 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
304 var ft_coloring
= new NaiveFTColoring(self.class_coloring
)
305 self.ft_colors
= ft_coloring
.colorize
306 self.ft_tables
= ft_coloring
.build_ft_tables
307 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
308 var ft_coloring
= new FTModPerfectHashing(self.class_coloring
)
309 self.ft_colors
= ft_coloring
.colorize
310 self.ft_masks
= ft_coloring
.compute_masks
311 self.ft_tables
= ft_coloring
.build_ft_tables
312 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
313 var ft_coloring
= new FTAndPerfectHashing(self.class_coloring
)
314 self.ft_colors
= ft_coloring
.colorize
315 self.ft_masks
= ft_coloring
.compute_masks
316 self.ft_tables
= ft_coloring
.build_ft_tables
318 var ft_coloring
= new FTColoring(self.class_coloring
)
319 self.ft_colors
= ft_coloring
.colorize
320 self.ft_tables
= ft_coloring
.build_ft_tables
322 self.compile_color_consts
(self.ft_colors
.as(not null))
324 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
325 # colorize live entries
327 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
328 entries_coloring
= new NaiveLiveEntryColoring
330 entries_coloring
= new LiveEntryColoring
332 self.livetypes_colors
= entries_coloring
.colorize
(mtypes
)
333 self.livetypes_tables
= entries_coloring
.build_livetype_tables
(mtypes
)
334 self.livetypes_tables_sizes
= entries_coloring
.livetypes_tables_sizes
336 self.compile_unanchored_tables
(mtypes
)
340 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
341 var type_coloring
= new NaiveTypeColoring(self.mainmodule
, mtypes
)
342 self.type_colors
= type_coloring
.colorize
(mtypes
)
343 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
344 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
345 var type_coloring
= new TypeModPerfectHashing(self.mainmodule
, mtypes
)
346 self.type_colors
= type_coloring
.compute_masks
(mtypes
, typeids
)
347 self.type_tables
= type_coloring
.hash_type_tables
(mtypes
, typeids
, type_colors
)
349 self.header
.add_decl
("int HASH(int, int);")
351 v
.add_decl
("int HASH(int mask, int id) \{")
352 v
.add_decl
("return mask % id;")
354 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
355 var type_coloring
= new TypeAndPerfectHashing(self.mainmodule
, mtypes
)
356 self.type_colors
= type_coloring
.compute_masks
(mtypes
, typeids
)
357 self.type_tables
= type_coloring
.hash_type_tables
(mtypes
, typeids
, type_colors
)
359 self.header
.add_decl
("int HASH(int, int);")
361 v
.add_decl
("int HASH(int mask, int id) \{")
362 v
.add_decl
("return mask & id;")
365 var type_coloring
= new TypeColoring(self.mainmodule
, mtypes
)
366 self.type_colors
= type_coloring
.colorize
(mtypes
)
367 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
371 # for the class_name and output_class_name methods
372 self.compile_class_names
377 protected fun compile_unanchored_tables
(mtypes
: Set[MType]) do
378 var mtype2anchored
= new HashMap[MClassType, Set[MClassType]]
380 for mtype
in self.runtime_type_analysis
.live_types
do
381 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
382 if self.live_unanchored_types
.has_key
(cd
) then
383 if not mtype2anchored
.has_key
(mtype
) then
384 mtype2anchored
[mtype
] = new HashSet[MClassType]
386 for unanchored
in self.live_unanchored_types
[cd
] do
387 var anchored
= unanchored
.anchor_to
(self.mainmodule
, mtype
)
388 if anchored
isa MClassType then
389 mtype2anchored
[mtype
].add
(anchored
)
390 else if anchored
isa MNullableType then
391 mtype2anchored
[mtype
].add
(anchored
.mtype
.as(MClassType))
393 print
"NOT YET IMPLEMENTED: try compile_unanchored_tables with {unanchored}"
400 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
401 var unanchored_type_coloring
= new NaiveUnanchoredTypeColoring
402 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2anchored
)
403 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2anchored
)
404 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
405 var unanchored_type_coloring
= new UnanchoredTypeModPerfectHashing
406 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2anchored
)
407 self.unanchored_types_masks
= unanchored_type_coloring
.compute_masks
(mtype2anchored
)
408 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2anchored
)
409 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
410 var unanchored_type_coloring
= new UnanchoredTypeAndPerfectHashing
411 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2anchored
)
412 self.unanchored_types_masks
= unanchored_type_coloring
.compute_masks
(mtype2anchored
)
413 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2anchored
)
415 var unanchored_type_coloring
= new UnanchoredTypeColoring
416 self.unanchored_types_colors
= unanchored_type_coloring
.colorize
(mtype2anchored
)
417 self.unanchored_types_tables
= unanchored_type_coloring
.build_tables
(mtype2anchored
)
420 var unanchored_mtypes
= new HashMap[MType, Int]
421 for mclass
in modelbuilder
.model
.mclasses
do
422 var mtype
= mclass
.mclass_type
423 if unanchored_types_colors
.has_key
(mtype
) then
424 unanchored_mtypes
[mtype
] = unanchored_types_colors
[mtype
]
426 unanchored_mtypes
[mtype
] = -1
429 for mtype
, color
in unanchored_types_colors
.as(not null) do
430 unanchored_mtypes
[mtype
] = color
432 self.compile_color_consts
(unanchored_mtypes
)
435 #for k, v in unanchored_types_tables.as(not null) do
436 # print "{k}: {v.join(", ")}"
441 fun retieve_live_partial_types
(mtype
: MType) do
442 # add formal types arguments to mtypes
443 if mtype
isa MGenericType then
444 for ft
in mtype
.arguments
do
445 if ft
.need_anchor
then
446 print
("Why do we need anchor here ?")
449 self.partial_types
.add
(ft
)
450 retieve_live_partial_types
(ft
)
453 var mclass_type
: MClassType
454 if mtype
isa MNullableType then
455 mclass_type
= mtype
.mtype
.as(MClassType)
457 mclass_type
= mtype
.as(MClassType)
460 # add virtual types to mtypes
461 for vt
in self.vt_tables
[mclass_type
.mclass
] do
463 var anchored
= vt
.bound
.anchor_to
(self.mainmodule
, mclass_type
)
464 self.partial_types
.add
(anchored
)
469 # declare live generic types tables selection
470 private fun compile_live_gentype_to_c
(mclass
: MClass) do
471 if mclass
.arity
> 0 then
472 if self.livetypes_tables
.has_key
(mclass
) then
473 var table
= self.livetypes_tables
[mclass
]
474 var sign
= self.livetypes_tables_sizes
[mclass
]
475 var table_buffer
= new Buffer.from
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}] = \{\n")
476 compile_livetype_table
(table
, table_buffer
, 1, mclass
.arity
)
477 table_buffer
.append
("\};")
479 var v
= new SeparateCompilerVisitor(self)
480 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
481 v
.add_decl
(table_buffer
.to_s
)
483 var sign
= new Array[Int].filled_with
(0, mclass
.arity
)
484 var v
= new SeparateCompilerVisitor(self)
485 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
486 v
.add_decl
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
491 private fun compile_livetype_table
(table
: Array[nullable Object], buffer
: Buffer, depth
: Int, max
: Int) do
495 buffer
.append
("NULL,\n")
497 buffer
.append
("\{\},\n")
499 else if obj
isa MClassType then
500 buffer
.append
("(struct type*) &type_{obj.c_name}, /* {obj} */\n")
501 else if obj
isa Array[nullable Object] then
502 buffer
.append
("\{\n")
503 compile_livetype_table
(obj
, buffer
, depth
+ 1, max
)
504 buffer
.append
("\},\n")
509 # Separately compile all the method definitions of the module
510 fun compile_module_to_c
(mmodule
: MModule)
512 for cd
in mmodule
.mclassdefs
do
513 for pd
in cd
.mpropdefs
do
514 if not pd
isa MMethodDef then continue
515 #print "compile {pd} @ {cd} @ {mmodule}"
516 var r
= new SeparateRuntimeFunction(pd
)
518 if true or cd
.bound_mtype
.ctype
!= "val*" then
519 var r2
= new VirtualRuntimeFunction(pd
)
520 r2
.compile_to_c
(self)
526 # Globaly compile the type structure of a live type
527 fun compile_type_to_c
(mtype
: MType)
529 var c_name
= mtype
.c_name
530 var v
= new SeparateCompilerVisitor(self)
531 v
.add_decl
("/* runtime type {mtype} */")
533 # extern const struct type_X
534 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
535 self.header
.add_decl
("struct type_{c_name} \{")
536 self.header
.add_decl
("int id;")
537 self.header
.add_decl
("int color;")
538 self.header
.add_decl
("short int is_nullable;")
539 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
540 self.header
.add_decl
("int livecolor;")
542 self.header
.add_decl
("const struct unanchored_table_{c_name} *types;")
544 self.header
.add_decl
("const struct vts_table_{c_name} *vts_table;")
545 self.header
.add_decl
("const struct fts_table_{c_name} *fts_table;")
546 self.header
.add_decl
("int table_size;")
547 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
548 self.header
.add_decl
("\};")
550 # const struct type_X
551 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
552 v
.add_decl
("{self.typeids[mtype]},")
553 v
.add_decl
("{self.type_colors[mtype]},")
554 if mtype
isa MNullableType then
559 if modelbuilder
.toolcontext
.opt_generic_tree
.value
then
560 v
.add_decl
("{self.livetypes_colors[mtype]},")
562 if (not mtype
isa MNullableType and self.unanchored_types_tables
.has_key
(mtype
.as(MClassType))) or (mtype
isa MNullableType and self.unanchored_types_tables
.has_key
(mtype
.mtype
.as(MClassType))) then
563 v
.add_decl
("&unanchored_table_{c_name},")
568 v
.add_decl
("&vts_table_{c_name},")
569 v
.add_decl
("&fts_table_{c_name},")
570 v
.add_decl
("{self.type_tables[mtype].length},")
572 for stype
in self.type_tables
[mtype
] do
573 if stype
== null then
574 v
.add_decl
("-1, /* empty */")
576 v
.add_decl
("{self.typeids[stype]}, /* {stype} */")
582 compile_type_fts_table
(mtype
)
583 compile_type_vts_table
(mtype
)
584 compile_type_unanchored_table
(mtype
)
587 protected fun compile_type_fts_table
(mtype
: MType) do
589 var mclass_type
: MClassType
590 if mtype
isa MNullableType then
591 mclass_type
= mtype
.mtype
.as(MClassType)
593 mclass_type
= mtype
.as(MClassType)
596 # extern const struct fst_table_X fst_table_X
597 self.header
.add_decl
("extern const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name};")
598 self.header
.add_decl
("struct fts_table_{mtype.c_name} \{")
599 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
600 self.header
.add_decl
("int mask;")
602 self.header
.add_decl
("struct type *fts[{self.ft_tables[mclass_type.mclass].length}];")
603 self.header
.add_decl
("\};")
605 # const struct fts_table_X fts_table_X
607 v
.add_decl
("const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name} = \{")
608 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
609 v
.add_decl
("{self.ft_masks[mclass_type.mclass]},")
612 for ft
in self.ft_tables
[mclass_type
.mclass
] do
614 v
.add_decl
("NULL, /* empty */")
617 if ft
.mclass
== mclass_type
.mclass
then
618 ntype
= mclass_type
.arguments
[ft
.rank
]
620 ntype
= ft
.anchor_to
(self.mainmodule
, mclass_type
)
622 if self.typeids
.has_key
(ntype
) then
623 v
.add_decl
("(struct type*)&type_{ntype.c_name}, /* {ft} ({ntype}) */")
625 v
.add_decl
("NULL, /* empty ({ft} not a live type) */")
633 protected fun compile_type_vts_table
(mtype
: MType) do
635 var mclass_type
: MClassType
636 if mtype
isa MNullableType then
637 mclass_type
= mtype
.mtype
.as(MClassType)
639 mclass_type
= mtype
.as(MClassType)
642 # extern const struct vts_table_X vts_table_X
643 self.header
.add_decl
("extern const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name};")
644 self.header
.add_decl
("struct vts_table_{mtype.c_name} \{")
645 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
646 self.header
.add_decl
("int mask;")
648 self.header
.add_decl
("struct type *vts[{self.vt_tables[mclass_type.mclass].length}];")
649 self.header
.add_decl
("\};")
651 # const struct vts_table_X vts_table_X
653 v
.add_decl
("const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name} = \{")
654 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
655 v
.add_decl
("{vt_masks[mclass_type.mclass]},")
659 for vt
in self.vt_tables
[mclass_type
.mclass
] do
661 v
.add_decl
("NULL, /* empty */")
664 if bound
== null then
665 #FIXME how can a bound be null here ?
666 print
"No bound found for virtual type {vt} ?"
670 if bound
isa MNullableType then
672 is_nullable
= "nullable_"
674 if bound
isa MVirtualType then
675 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
676 else if bound
isa MParameterType then
677 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
678 else if bound
isa MGenericType and bound
.need_anchor
then
679 bound
= bound
.anchor_to
(self.mainmodule
, mclass_type
)
680 else if bound
isa MClassType then
682 print
"NOT YET IMPLEMENTED: mtype_to_livetype with type: {bound}"
686 if self.typeids
.has_key
(bound
) then
687 v
.add_decl
("(struct type*)&type_{is_nullable}{bound.c_name}, /* {bound} */")
689 v
.add_decl
("NULL, /* dead type {bound} */")
698 fun compile_type_unanchored_table
(mtype
: MType) do
700 var mclass_type
: MClassType
701 if mtype
isa MNullableType then
702 mclass_type
= mtype
.mtype
.as(MClassType)
704 mclass_type
= mtype
.as(MClassType)
707 # extern const struct unanchored_table_X unanchored_table_X
708 self.header
.add_decl
("extern const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name};")
710 self.header
.add_decl
("struct unanchored_table_{mtype.c_name} \{")
711 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
712 self.header
.add_decl
("int mask;")
714 if not self.unanchored_types_tables
.has_key
(mclass_type
) then
715 self.header
.add_decl
("struct type *types[0];")
717 self.header
.add_decl
("struct type *types[{self.unanchored_types_tables[mclass_type].length}];")
719 self.header
.add_decl
("\};")
721 if self.unanchored_types_tables
.has_key
(mclass_type
) then
722 # const struct fts_table_X fts_table_X
724 v
.add_decl
("const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name} = \{")
725 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
726 v
.add_decl
("{self.unanchored_types_masks[mclass_type]},")
729 for t
in self.unanchored_types_tables
[mclass_type
] do
731 v
.add_decl
("NULL, /* empty */")
733 if self.typeids
.has_key
(t
) then
734 v
.add_decl
("(struct type*)&type_{t.c_name}, /* {t} */")
736 v
.add_decl
("NULL, /* empty ({t} not a live type) */")
745 # Globally compile the table of the class mclass
746 # In a link-time optimisation compiler, tables are globally computed
747 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
748 fun compile_class_to_c
(mclass
: MClass)
750 var mtype
= mclass
.intro
.bound_mtype
751 var c_name
= mclass
.c_name
753 var vft
= self.method_tables
[mclass
]
754 var attrs
= self.attr_tables
[mclass
]
757 v
.add_decl
("/* runtime class {c_name} */")
758 var idnum
= classids
.length
759 var idname
= "ID_" + c_name
760 self.classids
[mtype
] = idname
761 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
763 self.header
.add_decl
("struct class_{c_name} \{")
764 self.header
.add_decl
("int box_kind;")
765 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
766 self.header
.add_decl
("\};")
769 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
770 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
771 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
773 for i
in [0 .. vft
.length
[ do
774 var mpropdef
= vft
[i
]
775 if mpropdef
== null then
776 v
.add_decl
("NULL, /* empty */")
778 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
779 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
781 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
788 if mtype
.ctype
!= "val*" then
789 #Build instance struct
790 self.header
.add_decl
("struct instance_{c_name} \{")
791 self.header
.add_decl
("const struct type *type;")
792 self.header
.add_decl
("const struct class *class;")
793 self.header
.add_decl
("{mtype.ctype} value;")
794 self.header
.add_decl
("\};")
796 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
798 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
799 v
.add_decl
("/* allocate {mtype} */")
800 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
801 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
802 v
.add
("res->type = (struct type*) &type_{c_name};")
803 v
.add
("res->class = (struct class*) &class_{c_name};")
804 v
.add
("res->value = value;")
805 v
.add
("return (val*)res;")
810 var is_native_array
= mclass
.name
== "NativeArray"
813 if is_native_array
then
814 sig
= "int length, struct type* type"
816 sig
= "struct type* type"
819 #Build instance struct
820 #extern const struct instance_array__NativeArray instance_array__NativeArray;
821 self.header
.add_decl
("struct instance_{c_name} \{")
822 self.header
.add_decl
("const struct type *type;")
823 self.header
.add_decl
("const struct class *class;")
824 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
825 if is_native_array
then
826 # NativeArrays are just a instance header followed by an array of values
827 self.header
.add_decl
("val* values[0];")
829 self.header
.add_decl
("\};")
832 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
833 v
.add_decl
("/* allocate {mtype} */")
834 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
835 var res
= v
.new_named_var
(mtype
, "self")
837 if is_native_array
then
838 var mtype_elt
= mtype
.arguments
.first
839 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
841 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
843 #v.add("{res} = calloc(sizeof(struct instance_{c_name}), 1);")
844 v
.add
("{res}->type = type;")
845 v
.add
("{res}->class = (struct class*) &class_{c_name};")
847 self.generate_init_attr
(v
, res
, mtype
)
848 v
.add
("return {res};")
851 generate_check_init_instance
(mtype
)
854 redef fun generate_check_init_instance
(mtype
)
856 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
858 var v
= self.new_visitor
859 var c_name
= mtype
.mclass
.c_name
860 var res
= new RuntimeVariable("self", mtype
, mtype
)
861 self.header
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype});")
862 v
.add_decl
("/* allocate {mtype} */")
863 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
864 self.generate_check_attr
(v
, res
, mtype
)
868 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
871 # The C function associated to a methoddef separately compiled
872 class SeparateRuntimeFunction
873 super AbstractRuntimeFunction
875 redef fun build_c_name
: String
877 return "{mmethoddef.c_name}"
880 redef fun to_s
do return self.mmethoddef
.to_s
882 redef fun compile_to_c
(compiler
)
884 var mmethoddef
= self.mmethoddef
886 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
887 var v
= compiler
.new_visitor
888 var selfvar
= new RuntimeVariable("self", recv
, recv
)
889 var arguments
= new Array[RuntimeVariable]
890 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
893 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
896 var comment
= new Buffer
897 var ret
= msignature
.return_mtype
899 sig
.append
("{ret.ctype} ")
900 else if mmethoddef
.mproperty
.is_new
then
902 sig
.append
("{ret.ctype} ")
906 sig
.append
(self.c_name
)
907 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
908 comment
.append
("(self: {selfvar}")
909 arguments
.add
(selfvar
)
910 for i
in [0..msignature
.arity
[ do
911 var mtype
= msignature
.mparameters
[i
].mtype
912 if i
== msignature
.vararg_rank
then
913 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
915 comment
.append
(", {mtype}")
916 sig
.append
(", {mtype.ctype} p{i}")
917 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
918 arguments
.add
(argvar
)
923 comment
.append
(": {ret}")
925 compiler
.header
.add_decl
("{sig};")
927 v
.add_decl
("/* method {self} for {comment} */")
928 v
.add_decl
("{sig} \{")
930 frame
.returnvar
= v
.new_var
(ret
)
932 frame
.returnlabel
= v
.get_name
("RET_LABEL")
934 if recv
!= arguments
.first
.mtype
then
935 #print "{self} {recv} {arguments.first}"
937 mmethoddef
.compile_inside_to_c
(v
, arguments
)
939 v
.add
("{frame.returnlabel.as(not null)}:;")
941 v
.add
("return {frame.returnvar.as(not null)};")
947 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
948 # The first parameter (the reciever) is always typed by val* in order to accept an object value
949 class VirtualRuntimeFunction
950 super AbstractRuntimeFunction
952 redef fun build_c_name
: String
954 return "VIRTUAL_{mmethoddef.c_name}"
957 redef fun to_s
do return self.mmethoddef
.to_s
959 redef fun compile_to_c
(compiler
)
961 var mmethoddef
= self.mmethoddef
963 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
964 var v
= compiler
.new_visitor
965 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
966 var arguments
= new Array[RuntimeVariable]
967 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
971 var comment
= new Buffer
973 # Because the function is virtual, the signature must match the one of the original class
974 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
975 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
976 var ret
= msignature
.return_mtype
978 sig
.append
("{ret.ctype} ")
979 else if mmethoddef
.mproperty
.is_new
then
981 sig
.append
("{ret.ctype} ")
985 sig
.append
(self.c_name
)
986 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
987 comment
.append
("(self: {selfvar}")
988 arguments
.add
(selfvar
)
989 for i
in [0..msignature
.arity
[ do
990 var mtype
= msignature
.mparameters
[i
].mtype
991 if i
== msignature
.vararg_rank
then
992 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
994 comment
.append
(", {mtype}")
995 sig
.append
(", {mtype.ctype} p{i}")
996 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
997 arguments
.add
(argvar
)
1002 comment
.append
(": {ret}")
1004 compiler
.header
.add_decl
("{sig};")
1006 v
.add_decl
("/* method {self} for {comment} */")
1007 v
.add_decl
("{sig} \{")
1009 frame
.returnvar
= v
.new_var
(ret
)
1011 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1013 if recv
!= arguments
.first
.mtype
then
1014 #print "{self} {recv} {arguments.first}"
1016 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1018 v
.add
("{frame.returnlabel.as(not null)}:;")
1020 v
.add
("return {frame.returnvar.as(not null)};")
1025 redef fun call
(v
, arguments
)
1032 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
1033 class SeparateCompilerVisitor
1034 super GlobalCompilerVisitor # TODO better separation of concerns
1036 redef fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
1038 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
1039 var recv
= args
.first
1040 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
1041 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
1043 for i
in [0..msignature
.arity
[ do
1044 var t
= msignature
.mparameters
[i
].mtype
1045 if i
== msignature
.vararg_rank
then
1048 args
[i
+1] = self.autobox
(args
[i
+1], t
)
1052 # Box or unbox a value to another type iff a C type conversion is needed
1053 # ENSURE: result.mtype.ctype == mtype.ctype
1054 redef fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1056 if value
.mtype
== mtype
then
1058 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
1060 else if value
.mtype
.ctype
== "val*" then
1061 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
1062 else if mtype
.ctype
== "val*" then
1063 var valtype
= value
.mtype
.as(MClassType)
1064 var res
= self.new_var
(mtype
)
1065 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
1066 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
1067 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
1070 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
1073 # Bad things will appen!
1074 var res
= self.new_var
(mtype
)
1075 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
1076 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
1081 redef fun send
(mmethod
, arguments
)
1083 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1084 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
1087 var res
: nullable RuntimeVariable
1088 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
1089 var ret
= msignature
.return_mtype
1090 if mmethod
.is_new
then
1091 ret
= arguments
.first
.mtype
1092 res
= self.new_var
(ret
)
1093 else if ret
== null then
1096 res
= self.new_var
(ret
)
1102 var recv
= arguments
.first
1105 self.varargize
(msignature
, arguments
)
1106 for i
in [0..msignature
.arity
[ do
1107 var a
= arguments
[i
+1]
1108 var t
= msignature
.mparameters
[i
].mtype
1109 if i
== msignature
.vararg_rank
then
1110 t
= arguments
[i
+1].mcasttype
1112 s
.append
(", {t.ctype}")
1113 a
= self.autobox
(a
, t
)
1117 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1118 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1120 self.add
("if ({recv} == NULL) \{")
1121 if mmethod
.name
== "==" then
1123 var arg
= arguments
[1]
1124 if arg
.mcasttype
isa MNullableType then
1125 self.add
("{res} = ({arg} == NULL);")
1126 else if arg
.mcasttype
isa MNullType then
1127 self.add
("{res} = 1; /* is null */")
1129 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1131 else if mmethod
.name
== "!=" then
1133 var arg
= arguments
[1]
1134 if arg
.mcasttype
isa MNullableType then
1135 self.add
("{res} = ({arg} != NULL);")
1136 else if arg
.mcasttype
isa MNullType then
1137 self.add
("{res} = 0; /* is null */")
1139 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1142 self.add_abort
("Reciever is null")
1144 self.add
("\} else \{")
1148 if ret
== null then r
= "void" else r
= ret
.ctype
1149 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1152 self.add
("{res} = {call};")
1164 redef fun call
(mmethoddef
, recvtype
, arguments
)
1166 var res
: nullable RuntimeVariable
1167 var ret
= mmethoddef
.msignature
.return_mtype
1168 if mmethoddef
.mproperty
.is_new
then
1169 ret
= arguments
.first
.mtype
1170 res
= self.new_var
(ret
)
1171 else if ret
== null then
1174 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1175 res
= self.new_var
(ret
)
1178 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1179 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1180 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1181 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1182 frame
.returnlabel
= self.get_name
("RET_LABEL")
1183 frame
.returnvar
= res
1184 var old_frame
= self.frame
1186 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1187 mmethoddef
.compile_inside_to_c
(self, arguments
)
1188 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1190 self.frame
= old_frame
1195 self.adapt_signature
(mmethoddef
, arguments
)
1198 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1201 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1207 redef fun isset_attribute
(a
, recv
)
1209 self.check_recv_notnull
(recv
)
1210 var res
= self.new_var
(bool_type
)
1211 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1215 redef fun read_attribute
(a
, recv
)
1217 self.check_recv_notnull
(recv
)
1219 # What is the declared type of the attribute?
1220 var ret
= a
.intro
.static_mtype
.as(not null)
1221 var intromclassdef
= a
.intro
.mclassdef
1222 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1224 # Get the attribute or a box (ie. always a val*)
1225 var cret
= self.object_type
.as_nullable
1226 var res
= self.new_var
(cret
)
1228 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1230 # Check for Uninitialized attribute
1231 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1232 self.add
("if ({res} == NULL) \{")
1233 self.add_abort
("Uninitialized attribute {a.name}")
1237 # Return the attribute or its unboxed version
1238 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1239 return self.autobox
(res
, ret
)
1242 redef fun write_attribute
(a
, recv
, value
)
1244 self.check_recv_notnull
(recv
)
1246 # What is the declared type of the attribute?
1247 var mtype
= a
.intro
.static_mtype
.as(not null)
1248 var intromclassdef
= a
.intro
.mclassdef
1249 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1251 # Adapt the value to the declared type
1252 value
= self.autobox
(value
, mtype
)
1253 var attr
= "{recv}->attrs[{a.const_color}]"
1254 if mtype
.ctype
!= "val*" then
1255 assert mtype
isa MClassType
1256 # The attribute is primitive, thus we store it in a box
1257 # The trick is to create the box the first time then resuse the box
1258 self.add
("if ({attr} != NULL) \{")
1259 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1260 self.add
("\} else \{")
1261 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1262 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1265 # The attribute is not primitive, thus store it direclty
1266 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1270 # Build livetype structure retrieving
1271 #ENSURE: mtype.need_anchor
1272 fun retrieve_anchored_livetype
(mtype
: MGenericType, buffer
: Buffer) do
1273 assert mtype
.need_anchor
1275 var compiler
= self.compiler
.as(SeparateCompiler)
1276 for ft
in mtype
.arguments
do
1280 if ntype
isa MNullableType then
1284 if ntype
isa MParameterType then
1285 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1286 buffer
.append
("[self->type->fts_table->types[HASH(self->type->fts_table->mask, {ntype.const_color})]->livecolor]")
1288 buffer
.append
("[self->type->fts_table->types[{ntype.const_color}]->livecolor]")
1290 else if ntype
isa MVirtualType then
1291 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1292 buffer
.append
("[self->type->vts_table->types[HASH(self->type->vts_table->mask, {ntype.mproperty.const_color})]->livecolor]")
1294 buffer
.append
("[self->type->vts_table->types[{ntype.mproperty.const_color}]->livecolor]")
1296 else if ntype
isa MGenericType and ntype
.need_anchor
then
1297 var bbuff
= new Buffer
1298 retrieve_anchored_livetype
(ntype
, bbuff
)
1299 buffer
.append
("[livetypes_{ntype.mclass.c_name}{bbuff.to_s}->livecolor]")
1300 else if ntype
isa MClassType then
1301 compiler
.undead_types
.add
(ft
)
1302 buffer
.append
("[type_{ft.c_name}.livecolor]")
1304 self.add
("printf(\"NOT YET IMPLEMENTED: init_instance
(%s
, {mtype}).\\n\
", \"{ft}\
"); exit(1);")
1309 redef fun init_instance
(mtype
)
1311 var compiler
= self.compiler
.as(SeparateCompiler)
1312 if mtype
isa MGenericType and mtype
.need_anchor
then
1313 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1314 var buff
= new Buffer
1315 retrieve_anchored_livetype
(mtype
, buff
)
1316 mtype
= self.anchor
(mtype
).as(MClassType)
1317 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
1319 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1320 var recv
= self.frame
.arguments
.first
1321 var recv_boxed
= self.autobox
(recv
, self.object_type
)
1322 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1323 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_boxed}->type->unanchored_table->types[HASH({recv_boxed}->type->unanchored_table->mask, {mtype.mclass.mclass_type.const_color})])", mtype
)
1325 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_boxed}->type->unanchored_table->types[{mtype.mclass.mclass_type.const_color}])", mtype
)
1329 compiler
.undead_types
.add
(mtype
)
1330 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
1333 redef fun check_init_instance
(value
, mtype
)
1335 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1336 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1340 redef fun type_test
(value
, mtype
)
1342 self.add
("/* {value.inspect} isa {mtype} */")
1343 var compiler
= self.compiler
.as(SeparateCompiler)
1345 var recv
= self.frame
.arguments
.first
1346 var recv_boxed
= self.autobox
(recv
, self.object_type
)
1348 var res
= self.new_var
(bool_type
)
1350 var type_struct
= self.get_name
("type_struct")
1351 self.add_decl
("struct type* {type_struct};")
1352 var cltype
= self.get_name
("cltype")
1353 self.add_decl
("int {cltype};")
1354 var idtype
= self.get_name
("idtype")
1355 self.add_decl
("int {idtype};")
1356 var is_nullable
= self.get_name
("is_nullable")
1357 self.add_decl
("short int {is_nullable};")
1359 var boxed
= self.autobox
(value
, self.object_type
)
1361 if not compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
and mtype
.need_anchor
then
1362 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1366 if ntype
isa MNullableType then
1370 if ntype
isa MParameterType then
1371 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1372 self.add
("{type_struct} = {recv_boxed}->type->fts_table->types[HASH({recv_boxed}->type->fts_table->mask, {ntype.const_color})];")
1374 self.add
("{type_struct} = {recv_boxed}->type->fts_table->types[{ntype.const_color}];")
1376 self.add
("{cltype} = {type_struct}->color;")
1377 self.add
("{idtype} = {type_struct}->id;")
1378 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1379 else if ntype
isa MGenericType and ntype
.need_anchor
then
1380 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
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};")
1384 self.add
("{cltype} = {type_struct}->color;")
1385 self.add
("{idtype} = {type_struct}->id;")
1386 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1388 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1389 self.add
("{type_struct} = {recv_boxed}->type->unanchored_table->types[HASH({recv_boxed}->type->unanchored_table->mask, {ntype.mclass.mclass_type.const_color})];")
1391 self.add
("{type_struct} = {recv_boxed}->type->unanchored_table->types[{ntype.mclass.mclass_type.const_color}];")
1393 self.add
("{cltype} = {type_struct}->color;")
1394 self.add
("{idtype} = {type_struct}->id;")
1395 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;")
1402 else if ntype
isa MVirtualType then
1403 var vtcolor
= ntype
.mproperty
.const_color
1404 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1405 self.add
("{type_struct} = {recv_boxed}->type->vts_table->types[HASH({recv_boxed}->type->vts_table->mask, {vtcolor})];")
1407 self.add
("{type_struct} = {recv_boxed}->type->vts_table->types[{vtcolor}];")
1409 self.add
("{cltype} = {type_struct}->color;")
1410 self.add
("{idtype} = {type_struct}->id;")
1411 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1413 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{boxed.inspect}\
"); exit(1);")
1416 if mtype
isa MNullableType then
1417 self.add
("{is_nullable} = 1;")
1420 # check color is in table
1421 self.add
("if({boxed} == NULL) \{")
1422 self.add
("{res} = {is_nullable};")
1423 self.add
("\} else \{")
1424 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1425 self.add
("{cltype} = HASH({boxed}->type->color, {idtype});")
1427 self.add
("if({cltype} >= {boxed}->type->table_size) \{")
1428 self.add
("{res} = 0;")
1429 self.add
("\} else \{")
1430 self.add
("{res} = {boxed}->type->type_table[{cltype}] == {idtype};")
1437 redef fun is_same_type_test
(value1
, value2
)
1439 var res
= self.new_var
(bool_type
)
1440 # Swap values to be symetric
1441 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1446 if value1
.mtype
.ctype
!= "val*" then
1447 if value2
.mtype
== value1
.mtype
then
1448 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1449 else if value2
.mtype
.ctype
!= "val*" then
1450 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1452 var mtype1
= value1
.mtype
.as(MClassType)
1453 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1456 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1461 redef fun class_name_string
(value
)
1463 var res
= self.get_name
("var_class_name")
1464 self.add_decl
("const char *{res};")
1465 self.add
("{res} = class_names[{value}->type->id];")
1469 redef fun equal_test
(value1
, value2
)
1471 var res
= self.new_var
(bool_type
)
1472 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1477 if value1
.mtype
.ctype
!= "val*" then
1478 if value2
.mtype
== value1
.mtype
then
1479 self.add
("{res} = {value1} == {value2};")
1480 else if value2
.mtype
.ctype
!= "val*" then
1481 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1483 var mtype1
= value1
.mtype
.as(MClassType)
1484 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1485 self.add
("if ({res}) \{")
1486 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1491 var maybe_null
= true
1492 var test
= new Array[String]
1493 var t1
= value1
.mcasttype
1494 if t1
isa MNullableType then
1495 test
.add
("{value1} != NULL")
1500 var t2
= value2
.mcasttype
1501 if t2
isa MNullableType then
1502 test
.add
("{value2} != NULL")
1508 var incompatible
= false
1510 if t1
.ctype
!= "val*" then
1513 # No need to compare class
1514 else if t2
.ctype
!= "val*" then
1516 else if can_be_primitive
(value2
) then
1517 test
.add
("{value1}->class == {value2}->class")
1521 else if t2
.ctype
!= "val*" then
1523 if can_be_primitive
(value1
) then
1524 test
.add
("{value1}->class == {value2}->class")
1532 if incompatible
then
1534 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1537 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1541 if primitive
!= null then
1542 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1543 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1544 test
.add
("{value1}->class == {value2}->class")
1545 var s
= new Array[String]
1546 for t
, v
in self.compiler
.as(SeparateCompiler).box_kinds
do
1547 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1549 test
.add
("({s.join(" || ")})")
1551 self.add
("{res} = {value1} == {value2};")
1554 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1558 fun can_be_primitive
(value
: RuntimeVariable): Bool
1560 var t
= value
.mcasttype
1561 if t
isa MNullableType then t
= t
.mtype
1562 if not t
isa MClassType then return false
1563 var k
= t
.mclass
.kind
1564 return k
== interface_kind
or t
.ctype
!= "val*"
1567 fun maybe_null
(value
: RuntimeVariable): Bool
1569 var t
= value
.mcasttype
1570 return t
isa MNullableType or t
isa MNullType
1573 redef fun array_instance
(array
, elttype
)
1575 var nclass
= self.get_class
("NativeArray")
1576 var arrayclass
= self.get_class
("Array")
1577 var arraytype
= arrayclass
.get_mtype
([elttype
])
1578 var res
= self.init_instance
(arraytype
)
1579 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1580 var length
= self.int_instance
(array
.length
)
1581 var nat
= native_array_instance
(elttype
, length
)
1582 for i
in [0..array
.length
[ do
1583 var r
= self.autobox
(array
[i
], self.object_type
)
1584 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1586 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1587 self.check_init_instance
(res
, arraytype
)
1592 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1594 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1595 assert mtype
isa MGenericType
1596 var compiler
= self.compiler
.as(SeparateCompiler)
1597 if mtype
.need_anchor
then
1598 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1599 var buff
= new Buffer
1600 retrieve_anchored_livetype
(mtype
, buff
)
1601 mtype
= self.anchor
(mtype
).as(MClassType)
1602 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
1604 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1605 var recv
= self.frame
.arguments
.first
1606 var recv_boxed
= self.autobox
(recv
, self.object_type
)
1607 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1608 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_boxed}->type->unanchored_table->types[HASH({recv_boxed}->type->unanchored_table->mask, {mtype.mclass.mclass_type.const_color})])", mtype
)
1610 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_boxed}->type->unanchored_table->types[{mtype.mclass.mclass_type.const_color}])", mtype
)
1614 compiler
.undead_types
.add
(mtype
)
1615 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype
)
1618 redef fun native_array_def
(pname
, ret_type
, arguments
)
1620 var elttype
= arguments
.first
.mtype
1621 var nclass
= self.get_class
("NativeArray")
1622 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1623 if pname
== "[]" then
1624 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1626 else if pname
== "[]=" then
1627 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1629 else if pname
== "copy_to" then
1630 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1631 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1636 redef fun calloc_array
(ret_type
, arguments
)
1638 var ret
= ret_type
.as(MGenericType)
1639 var compiler
= self.compiler
.as(SeparateCompiler)
1640 compiler
.undead_types
.add
(ret
)
1641 var mclass
= self.get_class
("ArrayCapable")
1642 var nclass
= self.get_class
("NativeArray")
1644 if compiler
.modelbuilder
.toolcontext
.opt_generic_tree
.value
then
1645 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1646 self.ret
(self.new_expr
("NEW_{nclass.c_name}({arguments[1]}, (struct type*) livetypes_array__NativeArray[self->type->fts_table->types[{ft.const_color}]->livecolor])", ret_type
))
1648 var res
= nclass
.get_mtype
(mclass
.mclass_type
.arguments
)
1649 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, res
)
1650 var recv
= self.frame
.arguments
.first
1651 var recv_boxed
= self.autobox
(recv
, self.object_type
)
1652 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1653 self.ret
(self.new_expr
("NEW_{nclass.c_name}({arguments[1]}, (struct type *) {recv_boxed}->type->unanchored_table->types[HASH({recv_boxed}->type->unanchored_table->mask, {nclass.mclass_type.const_color})])", ret_type
))
1655 self.ret
(self.new_expr
("NEW_{nclass.c_name}({arguments[1]}, (struct type *) {recv_boxed}->type->unanchored_table->types[{nclass.mclass_type.const_color}])", ret_type
))
1660 fun link_unanchored_type
(mclassdef
: MClassDef, mtype
: MType) do
1661 assert mtype
.need_anchor
1662 var compiler
= self.compiler
.as(SeparateCompiler)
1663 if not compiler
.live_unanchored_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1664 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1666 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1671 # Return the name of the C structure associated to a Nit class
1672 fun c_name
: String do
1673 var res
= self.c_name_cache
1674 if res
!= null then return res
1675 res
= "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1676 self.c_name_cache
= res
1679 private var c_name_cache
: nullable String
1683 fun const_color
: String do return "COLOR_{c_name}"
1686 redef class MParameterType
1689 var res
= self.c_name_cache
1690 if res
!= null then return res
1691 res
= "{self.mclass.c_name}_FT{self.rank}"
1692 self.c_name_cache
= res
1697 redef class MNullableType
1700 var res
= self.c_name_cache
1701 if res
!= null then return res
1702 res
= "nullable_{self.mtype.c_name}"
1703 self.c_name_cache
= res
1708 redef class MProperty
1709 fun c_name
: String do
1710 var res
= self.c_name_cache
1711 if res
!= null then return res
1712 res
= "{self.intro.c_name}"
1713 self.c_name_cache
= res
1716 private var c_name_cache
: nullable String
1718 fun const_color
: String do return "COLOR_{c_name}"