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
18 import abstract_compiler
19 import layout_builders
20 import rapid_type_analysis
22 # Add separate compiler specific options
23 redef class ToolContext
25 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")
28 # --no-union-attribute
29 var opt_no_union_attribute
: OptionBool = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
30 # --no-shortcut-equate
31 var opt_no_shortcut_equate
: OptionBool = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
32 # --inline-coloring-numbers
33 var opt_inline_coloring_numbers
: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
34 # --use-naive-coloring
35 var opt_bm_typing
: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
36 # --use-mod-perfect-hashing
37 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")
40 # --generic-resolution-tree
41 var opt_typing_table_metrics
: OptionBool = new OptionBool("Enable static size measuring of tables used for typing and resolution", "--typing-table-metrics")
46 self.option_context
.add_option
(self.opt_separate
)
47 self.option_context
.add_option
(self.opt_no_inline_intern
)
48 self.option_context
.add_option
(self.opt_no_union_attribute
)
49 self.option_context
.add_option
(self.opt_no_shortcut_equate
)
50 self.option_context
.add_option
(self.opt_inline_coloring_numbers
)
51 self.option_context
.add_option
(self.opt_bm_typing
)
52 self.option_context
.add_option
(self.opt_phmod_typing
)
53 self.option_context
.add_option
(self.opt_phand_typing
)
54 self.option_context
.add_option
(self.opt_typing_table_metrics
)
58 redef class ModelBuilder
59 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
62 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
64 var compiler
= new SeparateCompiler(mainmodule
, self, runtime_type_analysis
)
65 compiler
.compile_header
67 # compile class structures
68 for m
in mainmodule
.in_importation
.greaters
do
69 for mclass
in m
.intro_mclasses
do
70 compiler
.compile_class_to_c
(mclass
)
74 # The main function of the C
76 compiler
.compile_main_function
79 for m
in mainmodule
.in_importation
.greaters
do
81 compiler
.compile_module_to_c
(m
)
84 # compile live & cast type structures
86 var mtypes
= compiler
.do_type_coloring
88 compiler
.compile_type_to_c
(t
)
91 compiler
.display_stats
93 write_and_make
(compiler
)
97 # Singleton that store the knowledge about the separate compilation process
98 class SeparateCompiler
99 super AbstractCompiler
102 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
104 # The result of the RTA (used to know live types and methods)
105 var runtime_type_analysis
: RapidTypeAnalysis
107 private var undead_types
: Set[MType] = new HashSet[MType]
108 private var partial_types
: Set[MType] = new HashSet[MType]
110 private var type_layout_builder
: TypingLayoutBuilder[MType]
111 private var type_layout
: nullable TypingLayout[MType]
112 private var type_tables
: nullable Map[MType, Array[nullable MType]] = null
114 private var live_unanchored_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
116 private var resolution_layout
: nullable ResolutionLayout
117 private var resolution_tables
: nullable Map[MClassType, Array[nullable MType]]
119 protected var method_layout
: nullable PropertyLayout[MMethod]
120 protected var method_tables
: Map[MClass, Array[nullable MPropDef]]
122 protected var attr_layout
: nullable PropertyLayout[MAttribute]
123 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]]
125 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis) do
127 self.header
= new_visitor
128 self.init_layout_builders
129 self.runtime_type_analysis
= runtime_type_analysis
130 self.do_property_coloring
131 self.compile_box_kinds
134 protected fun init_layout_builders
do
136 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
137 self.type_layout_builder
= new BMTypeLayoutBuilder(self.mainmodule
)
138 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
139 self.type_layout_builder
= new PHTypeLayoutBuilder(self.mainmodule
, new PHModOperator)
140 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
141 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
142 self.type_layout_builder
= new PHTypeLayoutBuilder(self.mainmodule
, new PHAndOperator)
143 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
145 self.type_layout_builder
= new CLTypeLayoutBuilder(self.mainmodule
)
149 redef fun compile_header_structs
do
150 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
151 self.compile_header_attribute_structs
152 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
154 # With unanchored_table, all live type resolution are stored in a big table: unanchored_table
155 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. */")
157 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
158 self.header
.add_decl
("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
160 self.header
.add_decl
("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
163 self.header
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
166 fun compile_header_attribute_structs
168 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
169 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
171 self.header
.add_decl
("typedef union \{")
172 self.header
.add_decl
("void* val;")
173 for c
, v
in self.box_kinds
do
174 var t
= c
.mclass_type
175 self.header
.add_decl
("{t.ctype} {t.ctypename};")
177 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
181 fun compile_box_kinds
183 # Collect all bas box class
184 # FIXME: this is not completely fine with a separate compilation scheme
185 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
186 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
187 if classes
== null then continue
188 assert classes
.length
== 1 else print classes
.join
(", ")
189 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
193 var box_kinds
= new HashMap[MClass, Int]
195 fun box_kind_of
(mclass
: MClass): Int
197 if mclass
.mclass_type
.ctype
== "val*" then
199 else if mclass
.kind
== extern_kind
then
200 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
202 return self.box_kinds
[mclass
]
207 fun compile_color_consts
(colors
: Map[Object, Int]) do
208 for m
, c
in colors
do
209 if color_consts_done
.has
(m
) then continue
210 if m
isa MProperty then
211 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
212 self.header
.add_decl
("#define {m.const_color} {c}")
214 self.header
.add_decl
("extern const int {m.const_color};")
215 self.header
.add
("const int {m.const_color} = {c};")
217 else if m
isa MType then
218 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
219 self.header
.add_decl
("#define {m.const_color} {c}")
221 self.header
.add_decl
("extern const int {m.const_color};")
222 self.header
.add
("const int {m.const_color} = {c};")
225 color_consts_done
.add
(m
)
229 private var color_consts_done
= new HashSet[Object]
231 # colorize classe properties
232 fun do_property_coloring
do
233 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
236 var method_coloring
= new CLPropertyLayoutBuilder[MMethod](mainmodule
)
237 var method_layout
= method_coloring
.build_layout
(mclasses
)
238 self.method_tables
= build_method_tables
(mclasses
, method_layout
)
239 self.compile_color_consts
(method_layout
.pos
)
240 self.method_layout
= method_layout
242 # attributes coloration
243 var attribute_coloring
= new CLPropertyLayoutBuilder[MAttribute](mainmodule
)
244 var attr_layout
= attribute_coloring
.build_layout
(mclasses
)
245 self.attr_tables
= build_attr_tables
(mclasses
, attr_layout
)
246 self.compile_color_consts
(attr_layout
.pos
)
247 self.attr_layout
= attr_layout
250 fun build_method_tables
(mclasses
: Set[MClass], layout
: PropertyLayout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
251 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
252 for mclass
in mclasses
do
253 var table
= new Array[nullable MPropDef]
254 # first, fill table from parents by reverse linearization order
255 var parents
= self.mainmodule
.super_mclasses
(mclass
)
256 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
258 for mproperty
in self.mainmodule
.properties
(parent
) do
259 if not mproperty
isa MMethod then continue
260 var color
= layout
.pos
[mproperty
]
261 if table
.length
<= color
then
262 for i
in [table
.length
.. color
[ do
266 for mpropdef
in mproperty
.mpropdefs
do
267 if mpropdef
.mclassdef
.mclass
== parent
then
268 table
[color
] = mpropdef
274 # then override with local properties
275 for mproperty
in self.mainmodule
.properties
(mclass
) do
276 if not mproperty
isa MMethod then continue
277 var color
= layout
.pos
[mproperty
]
278 if table
.length
<= color
then
279 for i
in [table
.length
.. color
[ do
283 for mpropdef
in mproperty
.mpropdefs
do
284 if mpropdef
.mclassdef
.mclass
== mclass
then
285 table
[color
] = mpropdef
289 tables
[mclass
] = table
294 fun build_attr_tables
(mclasses
: Set[MClass], layout
: PropertyLayout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
295 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
296 for mclass
in mclasses
do
297 var table
= new Array[nullable MPropDef]
298 # first, fill table from parents by reverse linearization order
299 var parents
= self.mainmodule
.super_mclasses
(mclass
)
300 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
302 for mproperty
in self.mainmodule
.properties
(parent
) do
303 if not mproperty
isa MAttribute then continue
304 var color
= layout
.pos
[mproperty
]
305 if table
.length
<= color
then
306 for i
in [table
.length
.. color
[ do
310 for mpropdef
in mproperty
.mpropdefs
do
311 if mpropdef
.mclassdef
.mclass
== parent
then
312 table
[color
] = mpropdef
318 # then override with local properties
319 for mproperty
in self.mainmodule
.properties
(mclass
) do
320 if not mproperty
isa MAttribute then continue
321 var color
= layout
.pos
[mproperty
]
322 if table
.length
<= color
then
323 for i
in [table
.length
.. color
[ do
327 for mpropdef
in mproperty
.mpropdefs
do
328 if mpropdef
.mclassdef
.mclass
== mclass
then
329 table
[color
] = mpropdef
333 tables
[mclass
] = table
338 # colorize live types of the program
339 private fun do_type_coloring
: Set[MType] do
340 var mtypes
= new HashSet[MType]
341 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
342 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
343 mtypes
.add_all
(self.undead_types
)
344 for c
in self.box_kinds
.keys
do
345 mtypes
.add
(c
.mclass_type
)
348 for mtype
in mtypes
do
349 retieve_live_partial_types
(mtype
)
351 mtypes
.add_all
(self.partial_types
)
354 self.type_layout
= self.type_layout_builder
.build_layout
(mtypes
)
355 self.type_tables
= self.build_type_tables
(mtypes
)
357 # VT and FT are stored with other unresolved types in the big unanchored_tables
358 self.compile_unanchored_tables
(mtypes
)
364 fun build_type_tables
(mtypes
: Set[MType]): Map[MType, Array[nullable MType]] do
365 var tables
= new HashMap[MType, Array[nullable MType]]
366 var layout
= self.type_layout
367 for mtype
in mtypes
do
368 var table
= new Array[nullable MType]
369 var supers
= new HashSet[MType]
370 supers
.add_all
(self.mainmodule
.super_mtypes
(mtype
, mtypes
))
374 if layout
isa PHTypingLayout[MType] then
375 color
= layout
.hashes
[mtype
][sup
]
377 color
= layout
.pos
[sup
]
379 if table
.length
<= color
then
380 for i
in [table
.length
.. color
[ do
386 tables
[mtype
] = table
391 protected fun compile_unanchored_tables
(mtypes
: Set[MType]) do
392 # Unanchored_tables is used to perform a type resolution at runtime in O(1)
394 # During the visit of the body of classes, live_unanchored_types are collected
396 # Collect all live_unanchored_types (visited in the body of classes)
398 # Determinate fo each livetype what are its possible requested anchored types
399 var mtype2unanchored
= new HashMap[MClassType, Set[MType]]
400 for mtype
in self.runtime_type_analysis
.live_types
do
401 var set
= new HashSet[MType]
402 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
403 if self.live_unanchored_types
.has_key
(cd
) then
404 set
.add_all
(self.live_unanchored_types
[cd
])
407 mtype2unanchored
[mtype
] = set
410 # Compute the table layout with the prefered method
411 var resolution_builder
: ResolutionLayoutBuilder
412 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
413 resolution_builder
= new BMResolutionLayoutBuilder
414 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
415 resolution_builder
= new PHResolutionLayoutBuilder(new PHModOperator)
416 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
417 resolution_builder
= new PHResolutionLayoutBuilder(new PHAndOperator)
419 resolution_builder
= new CLResolutionLayoutBuilder
421 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unanchored
)
422 self.resolution_tables
= self.build_resolution_tables
(mtype2unanchored
)
424 # Compile a C constant for each collected unanchored type.
425 # Either to a color, or to -1 if the unanchored type is dead (no live receiver can require it)
426 var all_unanchored
= new HashSet[MType]
427 for t
in self.live_unanchored_types
.values
do
428 all_unanchored
.add_all
(t
)
430 var all_unanchored_types_colors
= new HashMap[MType, Int]
431 for t
in all_unanchored
do
432 if self.resolution_layout
.pos
.has_key
(t
) then
433 all_unanchored_types_colors
[t
] = self.resolution_layout
.pos
[t
]
435 all_unanchored_types_colors
[t
] = -1
438 self.compile_color_consts
(all_unanchored_types_colors
)
441 #for k, v in unanchored_types_tables.as(not null) do
442 # print "{k}: {v.join(", ")}"
447 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
448 var tables
= new HashMap[MClassType, Array[nullable MType]]
449 var layout
= self.resolution_layout
450 for mclasstype
, mtypes
in elements
do
451 var table
= new Array[nullable MType]
452 for mtype
in mtypes
do
454 if layout
isa PHResolutionLayout then
455 color
= layout
.hashes
[mclasstype
][mtype
]
457 color
= layout
.pos
[mtype
]
459 if table
.length
<= color
then
460 for i
in [table
.length
.. color
[ do
466 tables
[mclasstype
] = table
471 fun retieve_live_partial_types
(mtype
: MType) do
472 # add formal types arguments to mtypes
473 if mtype
isa MGenericType then
474 for ft
in mtype
.arguments
do
475 if ft
.need_anchor
then
476 print
("Why do we need anchor here ?")
479 self.partial_types
.add
(ft
)
480 retieve_live_partial_types
(ft
)
483 var mclass_type
: MClassType
484 if mtype
isa MNullableType then
485 mclass_type
= mtype
.mtype
.as(MClassType)
487 mclass_type
= mtype
.as(MClassType)
490 # add virtual types to mtypes
491 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
492 if vt
isa MVirtualTypeProp then
493 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
494 self.partial_types
.add
(anchored
)
499 # Separately compile all the method definitions of the module
500 fun compile_module_to_c
(mmodule
: MModule)
502 var old_module
= self.mainmodule
503 self.mainmodule
= mmodule
504 for cd
in mmodule
.mclassdefs
do
505 for pd
in cd
.mpropdefs
do
506 if not pd
isa MMethodDef then continue
507 #print "compile {pd} @ {cd} @ {mmodule}"
508 var r
= new SeparateRuntimeFunction(pd
)
510 if true or cd
.bound_mtype
.ctype
!= "val*" then
511 var r2
= new VirtualRuntimeFunction(pd
)
512 r2
.compile_to_c
(self)
516 self.mainmodule
= old_module
519 # Globaly compile the type structure of a live type
520 fun compile_type_to_c
(mtype
: MType)
522 var c_name
= mtype
.c_name
523 var v
= new SeparateCompilerVisitor(self)
524 v
.add_decl
("/* runtime type {mtype} */")
526 # extern const struct type_X
527 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
528 self.header
.add_decl
("struct type_{c_name} \{")
529 self.header
.add_decl
("int id;")
530 self.header
.add_decl
("const char *name;")
531 self.header
.add_decl
("int color;")
532 self.header
.add_decl
("short int is_nullable;")
533 self.header
.add_decl
("const struct types *unanchored_table;")
534 self.header
.add_decl
("int table_size;")
535 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
536 self.header
.add_decl
("\};")
538 # const struct type_X
539 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
540 v
.add_decl
("{self.type_layout.ids[mtype]},")
541 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
542 var layout
= self.type_layout
543 if layout
isa PHTypingLayout[MType] then
544 v
.add_decl
("{layout.masks[mtype]},")
546 v
.add_decl
("{layout.pos[mtype]},")
548 if mtype
isa MNullableType then
553 if compile_type_unanchored_table
(mtype
) then
554 v
.add_decl
("(struct types*) &unanchored_table_{c_name},")
558 v
.add_decl
("{self.type_tables[mtype].length},")
560 for stype
in self.type_tables
[mtype
] do
561 if stype
== null then
562 v
.add_decl
("-1, /* empty */")
564 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
571 fun compile_type_unanchored_table
(mtype
: MType): Bool do
573 var mclass_type
: MClassType
574 if mtype
isa MNullableType then
575 mclass_type
= mtype
.mtype
.as(MClassType)
577 mclass_type
= mtype
.as(MClassType)
579 if not self.resolution_tables
.has_key
(mclass_type
) then return false
581 var layout
= self.resolution_layout
583 # extern const struct unanchored_table_X unanchored_table_X
584 self.header
.add_decl
("extern const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name};")
585 self.header
.add_decl
("struct unanchored_table_{mtype.c_name} \{")
586 if layout
isa PHResolutionLayout then
587 self.header
.add_decl
("int mask;")
589 self.header
.add_decl
("struct type *types[{self.resolution_tables[mclass_type].length}];")
590 self.header
.add_decl
("\};")
592 # const struct fts_table_X fts_table_X
594 v
.add_decl
("const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name} = \{")
595 if layout
isa PHResolutionLayout then
596 v
.add_decl
("{layout.masks[mclass_type]},")
599 for t
in self.resolution_tables
[mclass_type
] do
601 v
.add_decl
("NULL, /* empty */")
603 # The table stores the result of the type resolution
604 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
605 # the value stored is tv.
606 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
607 # FIXME: What typeids means here? How can a tv not be live?
608 if self.type_layout
.ids
.has_key
(tv
) then
609 v
.add_decl
("(struct type*)&type_{tv.c_name}, /* {t}: {tv} */")
611 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
620 # Globally compile the table of the class mclass
621 # In a link-time optimisation compiler, tables are globally computed
622 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
623 fun compile_class_to_c
(mclass
: MClass)
625 var mtype
= mclass
.intro
.bound_mtype
626 var c_name
= mclass
.c_name
628 var vft
= self.method_tables
[mclass
]
629 var attrs
= self.attr_tables
[mclass
]
632 v
.add_decl
("/* runtime class {c_name} */")
633 var idnum
= classids
.length
634 var idname
= "ID_" + c_name
635 self.classids
[mtype
] = idname
636 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
638 self.header
.add_decl
("struct class_{c_name} \{")
639 self.header
.add_decl
("int box_kind;")
640 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
641 self.header
.add_decl
("\};")
644 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
645 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
646 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
648 for i
in [0 .. vft
.length
[ do
649 var mpropdef
= vft
[i
]
650 if mpropdef
== null then
651 v
.add_decl
("NULL, /* empty */")
653 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
654 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
656 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
663 if mtype
.ctype
!= "val*" then
664 #Build instance struct
665 self.header
.add_decl
("struct instance_{c_name} \{")
666 self.header
.add_decl
("const struct type *type;")
667 self.header
.add_decl
("const struct class *class;")
668 self.header
.add_decl
("{mtype.ctype} value;")
669 self.header
.add_decl
("\};")
671 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
673 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
674 v
.add_decl
("/* allocate {mtype} */")
675 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
676 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
677 v
.add
("res->type = (struct type*) &type_{c_name};")
678 v
.add
("res->class = (struct class*) &class_{c_name};")
679 v
.add
("res->value = value;")
680 v
.add
("return (val*)res;")
685 var is_native_array
= mclass
.name
== "NativeArray"
688 if is_native_array
then
689 sig
= "int length, struct type* type"
691 sig
= "struct type* type"
694 #Build instance struct
695 #extern const struct instance_array__NativeArray instance_array__NativeArray;
696 self.header
.add_decl
("struct instance_{c_name} \{")
697 self.header
.add_decl
("const struct type *type;")
698 self.header
.add_decl
("const struct class *class;")
699 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
700 if is_native_array
then
701 # NativeArrays are just a instance header followed by an array of values
702 self.header
.add_decl
("val* values[0];")
704 self.header
.add_decl
("\};")
707 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
708 v
.add_decl
("/* allocate {mtype} */")
709 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
710 var res
= v
.new_named_var
(mtype
, "self")
712 if is_native_array
then
713 var mtype_elt
= mtype
.arguments
.first
714 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
716 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
718 v
.add
("{res}->type = type;")
719 if v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then
720 v
.add
("if(type == NULL) \{")
721 v
.add_abort
("type null")
723 v
.add
("if(type->unanchored_table == NULL) \{")
724 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", type->name);")
725 v
.add_abort
("type dead")
728 v
.add
("{res}->class = (struct class*) &class_{c_name};")
730 self.generate_init_attr
(v
, res
, mtype
)
731 v
.add
("return {res};")
734 generate_check_init_instance
(mtype
)
737 redef fun generate_check_init_instance
(mtype
)
739 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
741 var v
= self.new_visitor
742 var c_name
= mtype
.mclass
.c_name
743 var res
= new RuntimeVariable("self", mtype
, mtype
)
744 self.header
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype});")
745 v
.add_decl
("/* allocate {mtype} */")
746 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
747 self.generate_check_attr
(v
, res
, mtype
)
751 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
755 redef fun display_stats
758 if self.modelbuilder
.toolcontext
.opt_typing_table_metrics
.value
then
765 print
"# size of tables"
766 print
"\trs size\trs hole\tst size\tst hole"
771 var rtables
= resolution_tables
772 if rtables
!= null then
773 for unanch
, table
in rtables
do
774 rt_table
+= table
.length
775 for e
in table
do if e
== null then rt_holes
+= 1
779 var ttables
= type_tables
780 if ttables
!= null then
781 for t
, table
in ttables
do
782 st_table
+= table
.length
783 for e
in table
do if e
== null then st_holes
+= 1
786 print
"\t{rt_table}\t{rt_holes}\t{st_table}\t{st_holes}"
790 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
791 class SeparateCompilerVisitor
792 super AbstractCompilerVisitor
794 redef type COMPILER: SeparateCompiler
796 redef fun adapt_signature
(m
, args
)
798 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
799 var recv
= args
.first
800 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
801 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
803 for i
in [0..msignature
.arity
[ do
804 var t
= msignature
.mparameters
[i
].mtype
805 if i
== msignature
.vararg_rank
then
808 args
[i
+1] = self.autobox
(args
[i
+1], t
)
812 redef fun autobox
(value
, mtype
)
814 if value
.mtype
== mtype
then
816 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
818 else if value
.mtype
.ctype
== "val*" then
819 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
820 else if mtype
.ctype
== "val*" then
821 var valtype
= value
.mtype
.as(MClassType)
822 var res
= self.new_var
(mtype
)
823 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
824 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
825 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
828 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
831 # Bad things will appen!
832 var res
= self.new_var
(mtype
)
833 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
834 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
839 # Return a C expression returning the runtime type structure of the value
840 # The point of the method is to works also with primitives types.
841 fun type_info
(value
: RuntimeVariable): String
843 if value
.mtype
.ctype
== "val*" then
844 return "{value}->type"
846 return "(&type_{value.mtype.c_name})"
850 redef fun send
(mmethod
, arguments
)
852 if arguments
.first
.mcasttype
.ctype
!= "val*" then
853 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
856 var res
: nullable RuntimeVariable
857 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
858 var ret
= msignature
.return_mtype
859 if mmethod
.is_new
then
860 ret
= arguments
.first
.mtype
861 res
= self.new_var
(ret
)
862 else if ret
== null then
865 res
= self.new_var
(ret
)
871 var recv
= arguments
.first
874 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
875 for i
in [0..msignature
.arity
[ do
876 var a
= arguments
[i
+1]
877 var t
= msignature
.mparameters
[i
].mtype
878 if i
== msignature
.vararg_rank
then
879 t
= arguments
[i
+1].mcasttype
881 s
.append
(", {t.ctype}")
882 a
= self.autobox
(a
, t
)
886 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
887 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
889 self.add
("if ({recv} == NULL) \{")
890 if mmethod
.name
== "==" then
892 var arg
= arguments
[1]
893 if arg
.mcasttype
isa MNullableType then
894 self.add
("{res} = ({arg} == NULL);")
895 else if arg
.mcasttype
isa MNullType then
896 self.add
("{res} = 1; /* is null */")
898 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
900 else if mmethod
.name
== "!=" then
902 var arg
= arguments
[1]
903 if arg
.mcasttype
isa MNullableType then
904 self.add
("{res} = ({arg} != NULL);")
905 else if arg
.mcasttype
isa MNullType then
906 self.add
("{res} = 0; /* is null */")
908 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
911 self.add_abort
("Reciever is null")
913 self.add
("\} else \{")
915 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
917 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
918 var arg
= arguments
[1]
919 if arg
.mcasttype
isa MNullType then
920 if mmethod
.name
== "==" then
921 self.add
("{res} = 0; /* arg is null but recv is not */")
923 self.add
("{res} = 1; /* arg is null and recv is not */")
933 if ret
== null then r
= "void" else r
= ret
.ctype
934 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
937 self.add
("{res} = {call};")
949 redef fun call
(mmethoddef
, recvtype
, arguments
)
951 var res
: nullable RuntimeVariable
952 var ret
= mmethoddef
.msignature
.return_mtype
953 if mmethoddef
.mproperty
.is_new
then
954 ret
= arguments
.first
.mtype
955 res
= self.new_var
(ret
)
956 else if ret
== null then
959 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
960 res
= self.new_var
(ret
)
963 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
964 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
965 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
966 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
967 frame
.returnlabel
= self.get_name
("RET_LABEL")
968 frame
.returnvar
= res
969 var old_frame
= self.frame
971 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
972 mmethoddef
.compile_inside_to_c
(self, arguments
)
973 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
975 self.frame
= old_frame
980 self.adapt_signature
(mmethoddef
, arguments
)
983 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
986 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
992 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
994 # A vararg must be stored into an new array
995 # The trick is that the dymaic type of the array may depends on the receiver
996 # of the method (ie recv) if the static type is unresolved
997 # This is more complex than usual because the unanchored type must not be resolved
998 # with the current receiver (ie self).
999 # Therefore to isolate the resolution from self, a local Frame is created.
1000 # One can see this implementation as an inlined method of the receiver whose only
1001 # job is to allocate the array
1002 var old_frame
= self.frame
1003 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1005 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1006 var res
= self.array_instance
(varargs
, elttype
)
1007 self.frame
= old_frame
1011 redef fun isset_attribute
(a
, recv
)
1013 self.check_recv_notnull
(recv
)
1014 var res
= self.new_var
(bool_type
)
1016 # What is the declared type of the attribute?
1017 var mtype
= a
.intro
.static_mtype
.as(not null)
1018 var intromclassdef
= a
.intro
.mclassdef
1019 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1021 if mtype
isa MNullableType then
1022 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1026 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1027 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1030 if mtype
.ctype
== "val*" then
1031 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1033 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1039 redef fun read_attribute
(a
, recv
)
1041 self.check_recv_notnull
(recv
)
1043 # What is the declared type of the attribute?
1044 var ret
= a
.intro
.static_mtype
.as(not null)
1045 var intromclassdef
= a
.intro
.mclassdef
1046 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1048 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1049 # Get the attribute or a box (ie. always a val*)
1050 var cret
= self.object_type
.as_nullable
1051 var res
= self.new_var
(cret
)
1054 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1056 # Check for Uninitialized attribute
1057 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1058 self.add
("if ({res} == NULL) \{")
1059 self.add_abort
("Uninitialized attribute {a.name}")
1063 # Return the attribute or its unboxed version
1064 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1065 return self.autobox
(res
, ret
)
1067 var res
= self.new_var
(ret
)
1068 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1070 # Check for Uninitialized attribute
1071 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1072 self.add
("if ({res} == NULL) \{")
1073 self.add_abort
("Uninitialized attribute {a.name}")
1081 redef fun write_attribute
(a
, recv
, value
)
1083 self.check_recv_notnull
(recv
)
1085 # What is the declared type of the attribute?
1086 var mtype
= a
.intro
.static_mtype
.as(not null)
1087 var intromclassdef
= a
.intro
.mclassdef
1088 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1090 # Adapt the value to the declared type
1091 value
= self.autobox
(value
, mtype
)
1093 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1094 var attr
= "{recv}->attrs[{a.const_color}]"
1095 if mtype
.ctype
!= "val*" then
1096 assert mtype
isa MClassType
1097 # The attribute is primitive, thus we store it in a box
1098 # The trick is to create the box the first time then resuse the box
1099 self.add
("if ({attr} != NULL) \{")
1100 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1101 self.add
("\} else \{")
1102 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1103 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1106 # The attribute is not primitive, thus store it direclty
1107 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1110 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1114 redef fun init_instance
(mtype
)
1116 var compiler
= self.compiler
1117 if mtype
isa MGenericType and mtype
.need_anchor
then
1118 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1119 var recv
= self.frame
.arguments
.first
1120 var recv_type_info
= self.type_info
(recv
)
1121 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1122 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
)
1124 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1127 compiler
.undead_types
.add
(mtype
)
1128 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
1131 redef fun check_init_instance
(value
, mtype
)
1133 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1134 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1137 redef fun type_test
(value
, mtype
, tag
)
1139 self.add
("/* {value.inspect} isa {mtype} */")
1140 var compiler
= self.compiler
1142 var recv
= self.frame
.arguments
.first
1143 var recv_type_info
= self.type_info
(recv
)
1145 var res
= self.new_var
(bool_type
)
1147 var cltype
= self.get_name
("cltype")
1148 self.add_decl
("int {cltype};")
1149 var idtype
= self.get_name
("idtype")
1150 self.add_decl
("int {idtype};")
1152 var maybe_null
= self.maybe_null
(value
)
1153 var accept_null
= "0"
1155 if ntype
isa MNullableType then
1160 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1161 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1162 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1163 self.compiler
.count_type_test_skipped
[tag
] += 1
1164 self.add
("count_type_test_skipped_{tag}++;")
1169 if ntype
.need_anchor
then
1170 var type_struct
= self.get_name
("type_struct")
1171 self.add_decl
("struct type* {type_struct};")
1173 # Either with unanchored_table with a direct resolution
1174 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1175 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1176 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[HASH({recv_type_info}->unanchored_table->mask, {ntype.const_color})];")
1178 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[{ntype.const_color}];")
1180 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1181 self.compiler
.count_type_test_unresolved
[tag
] += 1
1182 self.add
("count_type_test_unresolved_{tag}++;")
1184 self.add
("{cltype} = {type_struct}->color;")
1185 self.add
("{idtype} = {type_struct}->id;")
1186 if maybe_null
and accept_null
== "0" then
1187 var is_nullable
= self.get_name
("is_nullable")
1188 self.add_decl
("short int {is_nullable};")
1189 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1190 accept_null
= is_nullable
.to_s
1192 else if ntype
isa MClassType then
1193 compiler
.undead_types
.add
(mtype
)
1194 self.add
("{cltype} = type_{mtype.c_name}.color;")
1195 self.add
("{idtype} = type_{mtype.c_name}.id;")
1196 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1197 self.compiler
.count_type_test_resolved
[tag
] += 1
1198 self.add
("count_type_test_resolved_{tag}++;")
1201 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1204 # check color is in table
1206 self.add
("if({value} == NULL) \{")
1207 self.add
("{res} = {accept_null};")
1208 self.add
("\} else \{")
1210 var value_type_info
= self.type_info
(value
)
1211 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1212 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1214 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1215 self.add
("{res} = 0;")
1216 self.add
("\} else \{")
1217 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1226 redef fun is_same_type_test
(value1
, value2
)
1228 var res
= self.new_var
(bool_type
)
1229 # Swap values to be symetric
1230 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1235 if value1
.mtype
.ctype
!= "val*" then
1236 if value2
.mtype
== value1
.mtype
then
1237 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1238 else if value2
.mtype
.ctype
!= "val*" then
1239 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1241 var mtype1
= value1
.mtype
.as(MClassType)
1242 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1245 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1250 redef fun class_name_string
(value
)
1252 var res
= self.get_name
("var_class_name")
1253 self.add_decl
("const char* {res};")
1254 if value
.mtype
.ctype
== "val*" then
1255 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1257 self.add
"{res} = type_{value.mtype.c_name}.name;"
1262 redef fun equal_test
(value1
, value2
)
1264 var res
= self.new_var
(bool_type
)
1265 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1270 if value1
.mtype
.ctype
!= "val*" then
1271 if value2
.mtype
== value1
.mtype
then
1272 self.add
("{res} = {value1} == {value2};")
1273 else if value2
.mtype
.ctype
!= "val*" then
1274 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1276 var mtype1
= value1
.mtype
.as(MClassType)
1277 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1278 self.add
("if ({res}) \{")
1279 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1284 var maybe_null
= true
1285 var test
= new Array[String]
1286 var t1
= value1
.mcasttype
1287 if t1
isa MNullableType then
1288 test
.add
("{value1} != NULL")
1293 var t2
= value2
.mcasttype
1294 if t2
isa MNullableType then
1295 test
.add
("{value2} != NULL")
1301 var incompatible
= false
1303 if t1
.ctype
!= "val*" then
1306 # No need to compare class
1307 else if t2
.ctype
!= "val*" then
1309 else if can_be_primitive
(value2
) then
1310 test
.add
("{value1}->class == {value2}->class")
1314 else if t2
.ctype
!= "val*" then
1316 if can_be_primitive
(value1
) then
1317 test
.add
("{value1}->class == {value2}->class")
1325 if incompatible
then
1327 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1330 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1334 if primitive
!= null then
1335 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1336 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1337 test
.add
("{value1}->class == {value2}->class")
1338 var s
= new Array[String]
1339 for t
, v
in self.compiler
.box_kinds
do
1340 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1342 test
.add
("({s.join(" || ")})")
1344 self.add
("{res} = {value1} == {value2};")
1347 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1351 fun can_be_primitive
(value
: RuntimeVariable): Bool
1353 var t
= value
.mcasttype
1354 if t
isa MNullableType then t
= t
.mtype
1355 if not t
isa MClassType then return false
1356 var k
= t
.mclass
.kind
1357 return k
== interface_kind
or t
.ctype
!= "val*"
1360 fun maybe_null
(value
: RuntimeVariable): Bool
1362 var t
= value
.mcasttype
1363 return t
isa MNullableType or t
isa MNullType
1366 redef fun array_instance
(array
, elttype
)
1368 var nclass
= self.get_class
("NativeArray")
1369 var arrayclass
= self.get_class
("Array")
1370 var arraytype
= arrayclass
.get_mtype
([elttype
])
1371 var res
= self.init_instance
(arraytype
)
1372 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1373 var length
= self.int_instance
(array
.length
)
1374 var nat
= native_array_instance
(elttype
, length
)
1375 for i
in [0..array
.length
[ do
1376 var r
= self.autobox
(array
[i
], self.object_type
)
1377 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1379 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1380 self.check_init_instance
(res
, arraytype
)
1385 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1387 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1388 assert mtype
isa MGenericType
1389 var compiler
= self.compiler
1390 if mtype
.need_anchor
then
1391 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1392 var recv
= self.frame
.arguments
.first
1393 var recv_type_info
= self.type_info
(recv
)
1394 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1395 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
)
1397 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1400 compiler
.undead_types
.add
(mtype
)
1401 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype
)
1404 redef fun native_array_def
(pname
, ret_type
, arguments
)
1406 var elttype
= arguments
.first
.mtype
1407 var nclass
= self.get_class
("NativeArray")
1408 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1409 if pname
== "[]" then
1410 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1412 else if pname
== "[]=" then
1413 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1415 else if pname
== "copy_to" then
1416 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1417 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1422 redef fun calloc_array
(ret_type
, arguments
)
1424 var mclass
= self.get_class
("ArrayCapable")
1425 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1426 var res
= self.native_array_instance
(ft
, arguments
[1])
1430 fun link_unanchored_type
(mclassdef
: MClassDef, mtype
: MType) do
1431 assert mtype
.need_anchor
1432 var compiler
= self.compiler
1433 if not compiler
.live_unanchored_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1434 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1436 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1440 # The C function associated to a methoddef separately compiled
1441 class SeparateRuntimeFunction
1442 super AbstractRuntimeFunction
1444 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1446 redef fun to_s
do return self.mmethoddef
.to_s
1448 redef fun compile_to_c
(compiler
)
1450 var mmethoddef
= self.mmethoddef
1452 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1453 var v
= compiler
.new_visitor
1454 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1455 var arguments
= new Array[RuntimeVariable]
1456 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1459 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1461 var sig
= new Buffer
1462 var comment
= new Buffer
1463 var ret
= msignature
.return_mtype
1465 sig
.append
("{ret.ctype} ")
1466 else if mmethoddef
.mproperty
.is_new
then
1468 sig
.append
("{ret.ctype} ")
1472 sig
.append
(self.c_name
)
1473 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1474 comment
.append
("(self: {selfvar}")
1475 arguments
.add
(selfvar
)
1476 for i
in [0..msignature
.arity
[ do
1477 var mtype
= msignature
.mparameters
[i
].mtype
1478 if i
== msignature
.vararg_rank
then
1479 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1481 comment
.append
(", {mtype}")
1482 sig
.append
(", {mtype.ctype} p{i}")
1483 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1484 arguments
.add
(argvar
)
1489 comment
.append
(": {ret}")
1491 compiler
.header
.add_decl
("{sig};")
1493 v
.add_decl
("/* method {self} for {comment} */")
1494 v
.add_decl
("{sig} \{")
1496 frame
.returnvar
= v
.new_var
(ret
)
1498 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1500 if recv
!= arguments
.first
.mtype
then
1501 #print "{self} {recv} {arguments.first}"
1503 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1505 v
.add
("{frame.returnlabel.as(not null)}:;")
1507 v
.add
("return {frame.returnvar.as(not null)};")
1513 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1514 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1515 class VirtualRuntimeFunction
1516 super AbstractRuntimeFunction
1518 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1520 redef fun to_s
do return self.mmethoddef
.to_s
1522 redef fun compile_to_c
(compiler
)
1524 var mmethoddef
= self.mmethoddef
1526 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1527 var v
= compiler
.new_visitor
1528 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1529 var arguments
= new Array[RuntimeVariable]
1530 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1533 var sig
= new Buffer
1534 var comment
= new Buffer
1536 # Because the function is virtual, the signature must match the one of the original class
1537 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1538 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1539 var ret
= msignature
.return_mtype
1541 sig
.append
("{ret.ctype} ")
1542 else if mmethoddef
.mproperty
.is_new
then
1544 sig
.append
("{ret.ctype} ")
1548 sig
.append
(self.c_name
)
1549 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1550 comment
.append
("(self: {selfvar}")
1551 arguments
.add
(selfvar
)
1552 for i
in [0..msignature
.arity
[ do
1553 var mtype
= msignature
.mparameters
[i
].mtype
1554 if i
== msignature
.vararg_rank
then
1555 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1557 comment
.append
(", {mtype}")
1558 sig
.append
(", {mtype.ctype} p{i}")
1559 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1560 arguments
.add
(argvar
)
1565 comment
.append
(": {ret}")
1567 compiler
.header
.add_decl
("{sig};")
1569 v
.add_decl
("/* method {self} for {comment} */")
1570 v
.add_decl
("{sig} \{")
1572 frame
.returnvar
= v
.new_var
(ret
)
1574 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1576 if recv
!= arguments
.first
.mtype
then
1577 #print "{self} {recv} {arguments.first}"
1579 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1581 v
.add
("{frame.returnlabel.as(not null)}:;")
1583 v
.add
("return {frame.returnvar.as(not null)};")
1589 redef fun call
(v
, arguments
) do abort
1593 fun const_color
: String do return "COLOR_{c_name}"
1596 redef class MProperty
1597 fun const_color
: String do return "COLOR_{c_name}"