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")
41 var opt_tables_metrics
: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-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_tables_metrics
)
58 redef class ModelBuilder
59 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
62 self.toolcontext
.info
("*** GENERATING C ***", 1)
64 var compiler
= new SeparateCompiler(mainmodule
, self, runtime_type_analysis
)
65 compiler
.compile_header
67 # compile class structures
68 self.toolcontext
.info
("Property coloring", 2)
69 compiler
.new_file
("{mainmodule.name}.classes")
70 compiler
.do_property_coloring
71 for m
in mainmodule
.in_importation
.greaters
do
72 for mclass
in m
.intro_mclasses
do
73 compiler
.compile_class_to_c
(mclass
)
77 # The main function of the C
78 compiler
.new_file
("{mainmodule.name}.main")
79 compiler
.compile_main_function
82 for m
in mainmodule
.in_importation
.greaters
do
83 self.toolcontext
.info
("Generate C for module {m}", 2)
84 compiler
.new_file
("{m.name}.sep")
85 compiler
.compile_module_to_c
(m
)
88 # compile live & cast type structures
89 self.toolcontext
.info
("Type coloring", 2)
90 compiler
.new_file
("{mainmodule.name}.types")
91 var mtypes
= compiler
.do_type_coloring
93 compiler
.compile_type_to_c
(t
)
96 compiler
.display_stats
99 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
100 write_and_make
(compiler
)
104 # Singleton that store the knowledge about the separate compilation process
105 class SeparateCompiler
106 super AbstractCompiler
108 # The result of the RTA (used to know live types and methods)
109 var runtime_type_analysis
: RapidTypeAnalysis
111 private var undead_types
: Set[MType] = new HashSet[MType]
112 private var partial_types
: Set[MType] = new HashSet[MType]
113 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
115 private var type_layout
: nullable Layout[MType]
116 private var resolution_layout
: nullable Layout[MType]
117 protected var method_layout
: nullable Layout[MMethod]
118 protected var attr_layout
: nullable Layout[MAttribute]
120 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis) do
121 super(mainmodule
, mmbuilder
)
122 var file
= new_file
("nit.common")
123 self.header
= new CodeWriter(file
)
124 self.runtime_type_analysis
= runtime_type_analysis
125 self.compile_box_kinds
128 redef fun compile_header_structs
do
129 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
130 self.compile_header_attribute_structs
131 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
133 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
134 self.header
.add_decl
("struct type \{ int id; const char *name; int color; short int is_nullable; const struct types *resolution_table; int table_size; int type_table[]; \}; /* general C type representing a Nit type. */")
135 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
137 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
138 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
140 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
143 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
144 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
145 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
146 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
149 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
152 fun compile_header_attribute_structs
154 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
155 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
157 self.header
.add_decl
("typedef union \{")
158 self.header
.add_decl
("void* val;")
159 for c
, v
in self.box_kinds
do
160 var t
= c
.mclass_type
161 self.header
.add_decl
("{t.ctype} {t.ctypename};")
163 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
167 fun compile_box_kinds
169 # Collect all bas box class
170 # FIXME: this is not completely fine with a separate compilation scheme
171 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
172 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
173 if classes
== null then continue
174 assert classes
.length
== 1 else print classes
.join
(", ")
175 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
179 var box_kinds
= new HashMap[MClass, Int]
181 fun box_kind_of
(mclass
: MClass): Int
183 if mclass
.mclass_type
.ctype
== "val*" then
185 else if mclass
.kind
== extern_kind
then
186 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
188 return self.box_kinds
[mclass
]
193 fun compile_color_consts
(colors
: Map[Object, Int]) do
195 for m
, c
in colors
do
196 if color_consts_done
.has
(m
) then continue
197 if m
isa MProperty then
198 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
199 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {c}")
201 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
202 v
.add
("const int {m.const_color} = {c};")
204 else if m
isa MType then
205 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
206 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {c}")
208 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
209 v
.add
("const int {m.const_color} = {c};")
212 color_consts_done
.add
(m
)
216 private var color_consts_done
= new HashSet[Object]
218 # colorize classe properties
219 fun do_property_coloring
do
220 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
223 var method_layout_builder
: PropertyLayoutBuilder[MMethod]
224 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
225 #FIXME PH and BM layouts too slow for large programs
226 #if modelbuilder.toolcontext.opt_bm_typing.value then
227 # method_layout_builder = new MMethodBMizer(self.mainmodule)
228 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
229 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
230 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
231 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
232 #else if modelbuilder.toolcontext.opt_phand_typing.value then
233 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
234 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
236 method_layout_builder
= new MMethodColorer(self.mainmodule
)
237 attribute_layout_builder
= new MAttributeColorer(self.mainmodule
)
241 var method_layout
= method_layout_builder
.build_layout
(mclasses
)
242 self.method_tables
= build_method_tables
(mclasses
, method_layout
)
243 self.compile_color_consts
(method_layout
.pos
)
244 self.method_layout
= method_layout
246 # attributes coloration
247 var attr_layout
= attribute_layout_builder
.build_layout
(mclasses
)
248 self.attr_tables
= build_attr_tables
(mclasses
, attr_layout
)
249 self.compile_color_consts
(attr_layout
.pos
)
250 self.attr_layout
= attr_layout
253 fun build_method_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
254 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
255 for mclass
in mclasses
do
256 var table
= new Array[nullable MPropDef]
257 # first, fill table from parents by reverse linearization order
258 var parents
= self.mainmodule
.super_mclasses
(mclass
)
259 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
261 for mproperty
in self.mainmodule
.properties
(parent
) do
262 if not mproperty
isa MMethod then continue
263 var color
= layout
.pos
[mproperty
]
264 if table
.length
<= color
then
265 for i
in [table
.length
.. color
[ do
269 for mpropdef
in mproperty
.mpropdefs
do
270 if mpropdef
.mclassdef
.mclass
== parent
then
271 table
[color
] = mpropdef
277 # then override with local properties
278 for mproperty
in self.mainmodule
.properties
(mclass
) do
279 if not mproperty
isa MMethod then continue
280 var color
= layout
.pos
[mproperty
]
281 if table
.length
<= color
then
282 for i
in [table
.length
.. color
[ do
286 for mpropdef
in mproperty
.mpropdefs
do
287 if mpropdef
.mclassdef
.mclass
== mclass
then
288 table
[color
] = mpropdef
292 tables
[mclass
] = table
297 fun build_attr_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
298 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
299 for mclass
in mclasses
do
300 var table
= new Array[nullable MPropDef]
301 # first, fill table from parents by reverse linearization order
302 var parents
= self.mainmodule
.super_mclasses
(mclass
)
303 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
305 for mproperty
in self.mainmodule
.properties
(parent
) do
306 if not mproperty
isa MAttribute then continue
307 var color
= layout
.pos
[mproperty
]
308 if table
.length
<= color
then
309 for i
in [table
.length
.. color
[ do
313 for mpropdef
in mproperty
.mpropdefs
do
314 if mpropdef
.mclassdef
.mclass
== parent
then
315 table
[color
] = mpropdef
321 # then override with local properties
322 for mproperty
in self.mainmodule
.properties
(mclass
) do
323 if not mproperty
isa MAttribute then continue
324 var color
= layout
.pos
[mproperty
]
325 if table
.length
<= color
then
326 for i
in [table
.length
.. color
[ do
330 for mpropdef
in mproperty
.mpropdefs
do
331 if mpropdef
.mclassdef
.mclass
== mclass
then
332 table
[color
] = mpropdef
336 tables
[mclass
] = table
341 # colorize live types of the program
342 private fun do_type_coloring
: Set[MType] do
343 var mtypes
= new HashSet[MType]
344 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
345 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
346 mtypes
.add_all
(self.undead_types
)
347 for c
in self.box_kinds
.keys
do
348 mtypes
.add
(c
.mclass_type
)
351 for mtype
in mtypes
do
352 retrieve_partial_types
(mtype
)
354 mtypes
.add_all
(self.partial_types
)
357 var layout_builder
: TypingLayoutBuilder[MType]
358 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
359 layout_builder
= new MTypeBMizer(self.mainmodule
)
360 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
361 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
362 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
363 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
365 layout_builder
= new MTypeColorer(self.mainmodule
)
369 self.type_layout
= layout_builder
.build_layout
(mtypes
)
370 self.type_tables
= self.build_type_tables
(mtypes
)
372 # VT and FT are stored with other unresolved types in the big resolution_tables
373 self.compile_resolution_tables
(mtypes
)
379 fun build_type_tables
(mtypes
: Set[MType]): Map[MType, Array[nullable MType]] do
380 var tables
= new HashMap[MType, Array[nullable MType]]
381 var layout
= self.type_layout
382 for mtype
in mtypes
do
383 var table
= new Array[nullable MType]
384 var supers
= new HashSet[MType]
385 supers
.add_all
(self.mainmodule
.super_mtypes
(mtype
, mtypes
))
389 if layout
isa PHLayout[MType, MType] then
390 color
= layout
.hashes
[mtype
][sup
]
392 color
= layout
.pos
[sup
]
394 if table
.length
<= color
then
395 for i
in [table
.length
.. color
[ do
401 tables
[mtype
] = table
406 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
407 # resolution_tables is used to perform a type resolution at runtime in O(1)
409 # During the visit of the body of classes, live_unresolved_types are collected
411 # Collect all live_unresolved_types (visited in the body of classes)
413 # Determinate fo each livetype what are its possible requested anchored types
414 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
415 for mtype
in self.runtime_type_analysis
.live_types
do
416 var set
= new HashSet[MType]
417 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
418 if self.live_unresolved_types
.has_key
(cd
) then
419 set
.add_all
(self.live_unresolved_types
[cd
])
422 mtype2unresolved
[mtype
] = set
425 # Compute the table layout with the prefered method
426 var resolution_builder
: ResolutionLayoutBuilder
427 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
428 resolution_builder
= new ResolutionBMizer
429 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
430 resolution_builder
= new ResolutionHasher(new PHModOperator)
431 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
432 resolution_builder
= new ResolutionHasher(new PHAndOperator)
434 resolution_builder
= new ResolutionColorer
436 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
437 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
439 # Compile a C constant for each collected unresolved type.
440 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
441 var all_unresolved
= new HashSet[MType]
442 for t
in self.live_unresolved_types
.values
do
443 all_unresolved
.add_all
(t
)
445 var all_unresolved_types_colors
= new HashMap[MType, Int]
446 for t
in all_unresolved
do
447 if self.resolution_layout
.pos
.has_key
(t
) then
448 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
450 all_unresolved_types_colors
[t
] = -1
453 self.compile_color_consts
(all_unresolved_types_colors
)
456 #for k, v in unresolved_types_tables.as(not null) do
457 # print "{k}: {v.join(", ")}"
462 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
463 var tables
= new HashMap[MClassType, Array[nullable MType]]
464 var layout
= self.resolution_layout
465 for mclasstype
, mtypes
in elements
do
466 var table
= new Array[nullable MType]
467 for mtype
in mtypes
do
469 if layout
isa PHLayout[MClassType, MType] then
470 color
= layout
.hashes
[mclasstype
][mtype
]
472 color
= layout
.pos
[mtype
]
474 if table
.length
<= color
then
475 for i
in [table
.length
.. color
[ do
481 tables
[mclasstype
] = table
486 fun retrieve_partial_types
(mtype
: MType) do
487 # add formal types arguments to mtypes
488 if mtype
isa MGenericType then
489 for ft
in mtype
.arguments
do
490 if ft
.need_anchor
then
491 print
("Why do we need anchor here ?")
494 self.partial_types
.add
(ft
)
495 retrieve_partial_types
(ft
)
498 var mclass_type
: MClassType
499 if mtype
isa MNullableType then
500 mclass_type
= mtype
.mtype
.as(MClassType)
502 mclass_type
= mtype
.as(MClassType)
505 # add virtual types to mtypes
506 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
507 if vt
isa MVirtualTypeProp then
508 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
509 self.partial_types
.add
(anchored
)
514 # Separately compile all the method definitions of the module
515 fun compile_module_to_c
(mmodule
: MModule)
517 var old_module
= self.mainmodule
518 self.mainmodule
= mmodule
519 for cd
in mmodule
.mclassdefs
do
520 for pd
in cd
.mpropdefs
do
521 if not pd
isa MMethodDef then continue
522 #print "compile {pd} @ {cd} @ {mmodule}"
523 var r
= pd
.separate_runtime_function
525 var r2
= pd
.virtual_runtime_function
526 r2
.compile_to_c
(self)
529 self.mainmodule
= old_module
532 # Globaly compile the type structure of a live type
533 fun compile_type_to_c
(mtype
: MType)
535 var c_name
= mtype
.c_name
536 var v
= new SeparateCompilerVisitor(self)
537 v
.add_decl
("/* runtime type {mtype} */")
539 # extern const struct type_X
540 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
542 # const struct type_X
543 v
.add_decl
("const struct type type_{c_name} = \{")
544 v
.add_decl
("{self.type_layout.ids[mtype]},")
545 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
546 var layout
= self.type_layout
547 if layout
isa PHLayout[MType, MType] then
548 v
.add_decl
("{layout.masks[mtype]},")
550 v
.add_decl
("{layout.pos[mtype]},")
552 if mtype
isa MNullableType then
557 if compile_type_resolution_table
(mtype
) then
558 v
.require_declaration
("resolution_table_{c_name}")
559 v
.add_decl
("&resolution_table_{c_name},")
563 v
.add_decl
("{self.type_tables[mtype].length},")
565 for stype
in self.type_tables
[mtype
] do
566 if stype
== null then
567 v
.add_decl
("-1, /* empty */")
569 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
576 fun compile_type_resolution_table
(mtype
: MType): Bool do
578 var mclass_type
: MClassType
579 if mtype
isa MNullableType then
580 mclass_type
= mtype
.mtype
.as(MClassType)
582 mclass_type
= mtype
.as(MClassType)
584 if not self.resolution_tables
.has_key
(mclass_type
) then return false
586 var layout
= self.resolution_layout
588 # extern const struct resolution_table_X resolution_table_X
589 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
591 # const struct fts_table_X fts_table_X
593 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
594 if layout
isa PHLayout[MClassType, MType] then
595 v
.add_decl
("{layout.masks[mclass_type]},")
597 v
.add_decl
("0, /* dummy */")
600 for t
in self.resolution_tables
[mclass_type
] do
602 v
.add_decl
("NULL, /* empty */")
604 # The table stores the result of the type resolution
605 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
606 # the value stored is tv.
607 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
608 # FIXME: What typeids means here? How can a tv not be live?
609 if self.type_layout
.ids
.has_key
(tv
) then
610 v
.require_declaration
("type_{tv.c_name}")
611 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
613 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
622 # Globally compile the table of the class mclass
623 # In a link-time optimisation compiler, tables are globally computed
624 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
625 fun compile_class_to_c
(mclass
: MClass)
627 var mtype
= mclass
.intro
.bound_mtype
628 var c_name
= mclass
.c_name
630 var vft
= self.method_tables
[mclass
]
631 var attrs
= self.attr_tables
[mclass
]
634 v
.add_decl
("/* runtime class {c_name} */")
637 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
638 v
.add_decl
("const struct class class_{c_name} = \{")
639 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
641 for i
in [0 .. vft
.length
[ do
642 var mpropdef
= vft
[i
]
643 if mpropdef
== null then
644 v
.add_decl
("NULL, /* empty */")
646 assert mpropdef
isa MMethodDef
647 var rf
= mpropdef
.virtual_runtime_function
648 v
.require_declaration
(rf
.c_name
)
649 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
655 if mtype
.ctype
!= "val*" then
656 #Build instance struct
657 self.header
.add_decl
("struct instance_{c_name} \{")
658 self.header
.add_decl
("const struct type *type;")
659 self.header
.add_decl
("const struct class *class;")
660 self.header
.add_decl
("{mtype.ctype} value;")
661 self.header
.add_decl
("\};")
663 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
666 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
667 v
.add_decl
("/* allocate {mtype} */")
668 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
669 v
.add
("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
670 v
.require_declaration
("type_{c_name}")
671 v
.add
("res->type = &type_{c_name};")
672 v
.require_declaration
("class_{c_name}")
673 v
.add
("res->class = &class_{c_name};")
674 v
.add
("res->value = value;")
675 v
.add
("return (val*)res;")
678 else if mclass
.name
== "NativeArray" then
679 #Build instance struct
680 self.header
.add_decl
("struct instance_{c_name} \{")
681 self.header
.add_decl
("const struct type *type;")
682 self.header
.add_decl
("const struct class *class;")
683 # NativeArrays are just a instance header followed by an array of values
684 self.header
.add_decl
("val* values[0];")
685 self.header
.add_decl
("\};")
688 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
689 v
.add_decl
("/* allocate {mtype} */")
690 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
691 var res
= v
.new_named_var
(mtype
, "self")
693 var mtype_elt
= mtype
.arguments
.first
694 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
695 v
.add
("{res}->type = type;")
696 hardening_live_type
(v
, "type")
697 v
.require_declaration
("class_{c_name}")
698 v
.add
("{res}->class = &class_{c_name};")
699 v
.add
("return {res};")
705 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
706 v
.add_decl
("/* allocate {mtype} */")
707 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
708 var res
= v
.new_named_var
(mtype
, "self")
710 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
711 v
.add
("{res}->type = type;")
712 hardening_live_type
(v
, "type")
713 v
.require_declaration
("class_{c_name}")
714 v
.add
("{res}->class = &class_{c_name};")
715 self.generate_init_attr
(v
, res
, mtype
)
716 v
.add
("return {res};")
719 generate_check_init_instance
(mtype
)
722 # Add a dynamic test to ensure that the type referenced by `t` is a live type
723 fun hardening_live_type
(v
: VISITOR, t
: String)
725 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
726 v
.add
("if({t} == NULL) \{")
727 v
.add_abort
("type null")
729 v
.add
("if({t}->resolution_table == NULL) \{")
730 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
731 v
.add_abort
("type dead")
735 redef fun generate_check_init_instance
(mtype
)
737 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
739 var v
= self.new_visitor
740 var c_name
= mtype
.mclass
.c_name
741 var res
= new RuntimeVariable("self", mtype
, mtype
)
742 self.provide_declaration
("CHECK_NEW_{c_name}", "void CHECK_NEW_{c_name}({mtype.ctype});")
743 v
.add_decl
("/* allocate {mtype} */")
744 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
745 self.generate_check_attr
(v
, res
, mtype
)
749 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
753 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
754 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
755 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
756 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
758 redef fun display_stats
761 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
768 print
"# size of subtyping tables"
769 print
"\ttotal \tholes"
772 for t
, table
in type_tables
do
773 total
+= table
.length
774 for e
in table
do if e
== null then holes
+= 1
776 print
"\t{total}\t{holes}"
778 print
"# size of resolution tables"
779 print
"\ttotal \tholes"
782 for t
, table
in resolution_tables
do
783 total
+= table
.length
784 for e
in table
do if e
== null then holes
+= 1
786 print
"\t{total}\t{holes}"
788 print
"# size of methods tables"
789 print
"\ttotal \tholes"
792 for t
, table
in method_tables
do
793 total
+= table
.length
794 for e
in table
do if e
== null then holes
+= 1
796 print
"\t{total}\t{holes}"
798 print
"# size of attributes tables"
799 print
"\ttotal \tholes"
802 for t
, table
in attr_tables
do
803 total
+= table
.length
804 for e
in table
do if e
== null then holes
+= 1
806 print
"\t{total}\t{holes}"
810 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
811 class SeparateCompilerVisitor
812 super AbstractCompilerVisitor
814 redef type COMPILER: SeparateCompiler
816 redef fun adapt_signature
(m
, args
)
818 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
819 var recv
= args
.first
820 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
821 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
823 for i
in [0..msignature
.arity
[ do
824 var t
= msignature
.mparameters
[i
].mtype
825 if i
== msignature
.vararg_rank
then
828 args
[i
+1] = self.autobox
(args
[i
+1], t
)
832 redef fun autobox
(value
, mtype
)
834 if value
.mtype
== mtype
then
836 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
838 else if value
.mtype
.ctype
== "val*" then
839 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
840 else if mtype
.ctype
== "val*" then
841 var valtype
= value
.mtype
.as(MClassType)
842 var res
= self.new_var
(mtype
)
843 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
844 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
845 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
848 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
851 # Bad things will appen!
852 var res
= self.new_var
(mtype
)
853 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
854 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
859 # Return a C expression returning the runtime type structure of the value
860 # The point of the method is to works also with primitives types.
861 fun type_info
(value
: RuntimeVariable): String
863 if value
.mtype
.ctype
== "val*" then
864 return "{value}->type"
866 self.require_declaration
("type_{value.mtype.c_name}")
867 return "(&type_{value.mtype.c_name})"
871 redef fun send
(mmethod
, arguments
)
873 if arguments
.first
.mcasttype
.ctype
!= "val*" then
874 # In order to shortcut the primitive, we need to find the most specific method
875 # Howverr, because of performance (no flattening), we always work on the realmainmodule
876 var m
= self.compiler
.mainmodule
877 self.compiler
.mainmodule
= self.compiler
.realmainmodule
878 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
879 self.compiler
.mainmodule
= m
883 var res
: nullable RuntimeVariable
884 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
885 var ret
= msignature
.return_mtype
886 if mmethod
.is_new
then
887 ret
= arguments
.first
.mtype
888 res
= self.new_var
(ret
)
889 else if ret
== null then
892 res
= self.new_var
(ret
)
898 var recv
= arguments
.first
901 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
902 for i
in [0..msignature
.arity
[ do
903 var a
= arguments
[i
+1]
904 var t
= msignature
.mparameters
[i
].mtype
905 if i
== msignature
.vararg_rank
then
906 t
= arguments
[i
+1].mcasttype
908 s
.append
(", {t.ctype}")
909 a
= self.autobox
(a
, t
)
913 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
914 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
916 self.add
("if ({recv} == NULL) \{")
917 if mmethod
.name
== "==" then
919 var arg
= arguments
[1]
920 if arg
.mcasttype
isa MNullableType then
921 self.add
("{res} = ({arg} == NULL);")
922 else if arg
.mcasttype
isa MNullType then
923 self.add
("{res} = 1; /* is null */")
925 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
927 else if mmethod
.name
== "!=" then
929 var arg
= arguments
[1]
930 if arg
.mcasttype
isa MNullableType then
931 self.add
("{res} = ({arg} != NULL);")
932 else if arg
.mcasttype
isa MNullType then
933 self.add
("{res} = 0; /* is null */")
935 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
938 self.add_abort
("Reciever is null")
940 self.add
("\} else \{")
942 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
944 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
945 var arg
= arguments
[1]
946 if arg
.mcasttype
isa MNullType then
947 if mmethod
.name
== "==" then
948 self.add
("{res} = 0; /* arg is null but recv is not */")
950 self.add
("{res} = 1; /* arg is null and recv is not */")
960 if ret
== null then r
= "void" else r
= ret
.ctype
961 self.require_declaration
(mmethod
.const_color
)
962 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
965 self.add
("{res} = {call};")
977 redef fun call
(mmethoddef
, recvtype
, arguments
)
979 var res
: nullable RuntimeVariable
980 var ret
= mmethoddef
.msignature
.return_mtype
981 if mmethoddef
.mproperty
.is_new
then
982 ret
= arguments
.first
.mtype
983 res
= self.new_var
(ret
)
984 else if ret
== null then
987 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
988 res
= self.new_var
(ret
)
991 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
992 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
993 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
994 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
995 frame
.returnlabel
= self.get_name
("RET_LABEL")
996 frame
.returnvar
= res
997 var old_frame
= self.frame
999 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1000 mmethoddef
.compile_inside_to_c
(self, arguments
)
1001 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1003 self.frame
= old_frame
1008 self.adapt_signature
(mmethoddef
, arguments
)
1010 self.require_declaration
(mmethoddef
.c_name
)
1012 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1015 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1021 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1023 # FIXME implements a polymorphic access in tables
1024 m
= m
.lookup_next_definition
(m
.mclassdef
.mmodule
, m
.mclassdef
.bound_mtype
)
1025 return self.call
(m
, recvtype
, args
)
1028 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1030 # A vararg must be stored into an new array
1031 # The trick is that the dymaic type of the array may depends on the receiver
1032 # of the method (ie recv) if the static type is unresolved
1033 # This is more complex than usual because the unresolved type must not be resolved
1034 # with the current receiver (ie self).
1035 # Therefore to isolate the resolution from self, a local Frame is created.
1036 # One can see this implementation as an inlined method of the receiver whose only
1037 # job is to allocate the array
1038 var old_frame
= self.frame
1039 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1041 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1042 var res
= self.array_instance
(varargs
, elttype
)
1043 self.frame
= old_frame
1047 redef fun isset_attribute
(a
, recv
)
1049 self.check_recv_notnull
(recv
)
1050 var res
= self.new_var
(bool_type
)
1052 # What is the declared type of the attribute?
1053 var mtype
= a
.intro
.static_mtype
.as(not null)
1054 var intromclassdef
= a
.intro
.mclassdef
1055 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1057 if mtype
isa MNullableType then
1058 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1062 self.require_declaration
(a
.const_color
)
1063 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1064 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1067 if mtype
.ctype
== "val*" then
1068 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1070 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1076 redef fun read_attribute
(a
, recv
)
1078 self.check_recv_notnull
(recv
)
1080 # What is the declared type of the attribute?
1081 var ret
= a
.intro
.static_mtype
.as(not null)
1082 var intromclassdef
= a
.intro
.mclassdef
1083 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1085 self.require_declaration
(a
.const_color
)
1086 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1087 # Get the attribute or a box (ie. always a val*)
1088 var cret
= self.object_type
.as_nullable
1089 var res
= self.new_var
(cret
)
1092 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1094 # Check for Uninitialized attribute
1095 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1096 self.add
("if ({res} == NULL) \{")
1097 self.add_abort
("Uninitialized attribute {a.name}")
1101 # Return the attribute or its unboxed version
1102 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1103 return self.autobox
(res
, ret
)
1105 var res
= self.new_var
(ret
)
1106 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1108 # Check for Uninitialized attribute
1109 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1110 self.add
("if ({res} == NULL) \{")
1111 self.add_abort
("Uninitialized attribute {a.name}")
1119 redef fun write_attribute
(a
, recv
, value
)
1121 self.check_recv_notnull
(recv
)
1123 # What is the declared type of the attribute?
1124 var mtype
= a
.intro
.static_mtype
.as(not null)
1125 var intromclassdef
= a
.intro
.mclassdef
1126 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1128 # Adapt the value to the declared type
1129 value
= self.autobox
(value
, mtype
)
1131 self.require_declaration
(a
.const_color
)
1132 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1133 var attr
= "{recv}->attrs[{a.const_color}]"
1134 if mtype
.ctype
!= "val*" then
1135 assert mtype
isa MClassType
1136 # The attribute is primitive, thus we store it in a box
1137 # The trick is to create the box the first time then resuse the box
1138 self.add
("if ({attr} != NULL) \{")
1139 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1140 self.add
("\} else \{")
1141 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1142 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1145 # The attribute is not primitive, thus store it direclty
1146 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1149 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1153 redef fun init_instance
(mtype
)
1155 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1156 var compiler
= self.compiler
1157 if mtype
isa MGenericType and mtype
.need_anchor
then
1158 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1159 var recv
= self.frame
.arguments
.first
1160 var recv_type_info
= self.type_info
(recv
)
1161 self.require_declaration
(mtype
.const_color
)
1162 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1163 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1165 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1168 compiler
.undead_types
.add
(mtype
)
1169 self.require_declaration
("type_{mtype.c_name}")
1170 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1173 redef fun check_init_instance
(value
, mtype
)
1175 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1176 self.require_declaration
("CHECK_NEW_{mtype.mclass.c_name}")
1177 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1180 redef fun type_test
(value
, mtype
, tag
)
1182 self.add
("/* {value.inspect} isa {mtype} */")
1183 var compiler
= self.compiler
1185 var recv
= self.frame
.arguments
.first
1186 var recv_type_info
= self.type_info
(recv
)
1188 var res
= self.new_var
(bool_type
)
1190 var cltype
= self.get_name
("cltype")
1191 self.add_decl
("int {cltype};")
1192 var idtype
= self.get_name
("idtype")
1193 self.add_decl
("int {idtype};")
1195 var maybe_null
= self.maybe_null
(value
)
1196 var accept_null
= "0"
1198 if ntype
isa MNullableType then
1203 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1204 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1205 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1206 self.compiler
.count_type_test_skipped
[tag
] += 1
1207 self.add
("count_type_test_skipped_{tag}++;")
1212 if ntype
.need_anchor
then
1213 var type_struct
= self.get_name
("type_struct")
1214 self.add_decl
("const struct type* {type_struct};")
1216 # Either with resolution_table with a direct resolution
1217 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1218 self.require_declaration
(ntype
.const_color
)
1219 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1220 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1222 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1224 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1225 self.compiler
.count_type_test_unresolved
[tag
] += 1
1226 self.add
("count_type_test_unresolved_{tag}++;")
1228 self.add
("{cltype} = {type_struct}->color;")
1229 self.add
("{idtype} = {type_struct}->id;")
1230 if maybe_null
and accept_null
== "0" then
1231 var is_nullable
= self.get_name
("is_nullable")
1232 self.add_decl
("short int {is_nullable};")
1233 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1234 accept_null
= is_nullable
.to_s
1236 else if ntype
isa MClassType then
1237 compiler
.undead_types
.add
(mtype
)
1238 self.require_declaration
("type_{mtype.c_name}")
1239 self.add
("{cltype} = type_{mtype.c_name}.color;")
1240 self.add
("{idtype} = type_{mtype.c_name}.id;")
1241 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1242 self.compiler
.count_type_test_resolved
[tag
] += 1
1243 self.add
("count_type_test_resolved_{tag}++;")
1246 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1249 # check color is in table
1251 self.add
("if({value} == NULL) \{")
1252 self.add
("{res} = {accept_null};")
1253 self.add
("\} else \{")
1255 var value_type_info
= self.type_info
(value
)
1256 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1257 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1259 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1260 self.add
("{res} = 0;")
1261 self.add
("\} else \{")
1262 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1271 redef fun is_same_type_test
(value1
, value2
)
1273 var res
= self.new_var
(bool_type
)
1274 # Swap values to be symetric
1275 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1280 if value1
.mtype
.ctype
!= "val*" then
1281 if value2
.mtype
== value1
.mtype
then
1282 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1283 else if value2
.mtype
.ctype
!= "val*" then
1284 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1286 var mtype1
= value1
.mtype
.as(MClassType)
1287 self.require_declaration
("class_{mtype1.c_name}")
1288 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1291 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1296 redef fun class_name_string
(value
)
1298 var res
= self.get_name
("var_class_name")
1299 self.add_decl
("const char* {res};")
1300 if value
.mtype
.ctype
== "val*" then
1301 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1303 self.require_declaration
("type_{value.mtype.c_name}")
1304 self.add
"{res} = type_{value.mtype.c_name}.name;"
1309 redef fun equal_test
(value1
, value2
)
1311 var res
= self.new_var
(bool_type
)
1312 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1317 if value1
.mtype
.ctype
!= "val*" then
1318 if value2
.mtype
== value1
.mtype
then
1319 self.add
("{res} = {value1} == {value2};")
1320 else if value2
.mtype
.ctype
!= "val*" then
1321 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1323 var mtype1
= value1
.mtype
.as(MClassType)
1324 self.require_declaration
("class_{mtype1.c_name}")
1325 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1326 self.add
("if ({res}) \{")
1327 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1332 var maybe_null
= true
1333 var test
= new Array[String]
1334 var t1
= value1
.mcasttype
1335 if t1
isa MNullableType then
1336 test
.add
("{value1} != NULL")
1341 var t2
= value2
.mcasttype
1342 if t2
isa MNullableType then
1343 test
.add
("{value2} != NULL")
1349 var incompatible
= false
1351 if t1
.ctype
!= "val*" then
1354 # No need to compare class
1355 else if t2
.ctype
!= "val*" then
1357 else if can_be_primitive
(value2
) then
1358 test
.add
("{value1}->class == {value2}->class")
1362 else if t2
.ctype
!= "val*" then
1364 if can_be_primitive
(value1
) then
1365 test
.add
("{value1}->class == {value2}->class")
1373 if incompatible
then
1375 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1378 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1382 if primitive
!= null then
1383 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1384 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1385 test
.add
("{value1}->class == {value2}->class")
1386 var s
= new Array[String]
1387 for t
, v
in self.compiler
.box_kinds
do
1388 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1390 test
.add
("({s.join(" || ")})")
1392 self.add
("{res} = {value1} == {value2};")
1395 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1399 fun can_be_primitive
(value
: RuntimeVariable): Bool
1401 var t
= value
.mcasttype
1402 if t
isa MNullableType then t
= t
.mtype
1403 if not t
isa MClassType then return false
1404 var k
= t
.mclass
.kind
1405 return k
== interface_kind
or t
.ctype
!= "val*"
1408 fun maybe_null
(value
: RuntimeVariable): Bool
1410 var t
= value
.mcasttype
1411 return t
isa MNullableType or t
isa MNullType
1414 redef fun array_instance
(array
, elttype
)
1416 var nclass
= self.get_class
("NativeArray")
1417 var arrayclass
= self.get_class
("Array")
1418 var arraytype
= arrayclass
.get_mtype
([elttype
])
1419 var res
= self.init_instance
(arraytype
)
1420 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1421 var length
= self.int_instance
(array
.length
)
1422 var nat
= native_array_instance
(elttype
, length
)
1423 for i
in [0..array
.length
[ do
1424 var r
= self.autobox
(array
[i
], self.object_type
)
1425 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1427 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1428 self.check_init_instance
(res
, arraytype
)
1433 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1435 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1436 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1437 assert mtype
isa MGenericType
1438 var compiler
= self.compiler
1439 if mtype
.need_anchor
then
1440 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1441 var recv
= self.frame
.arguments
.first
1442 var recv_type_info
= self.type_info
(recv
)
1443 self.require_declaration
(mtype
.const_color
)
1444 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1445 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1447 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1450 compiler
.undead_types
.add
(mtype
)
1451 self.require_declaration
("type_{mtype.c_name}")
1452 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1455 redef fun native_array_def
(pname
, ret_type
, arguments
)
1457 var elttype
= arguments
.first
.mtype
1458 var nclass
= self.get_class
("NativeArray")
1459 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1460 if pname
== "[]" then
1461 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1463 else if pname
== "[]=" then
1464 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1466 else if pname
== "copy_to" then
1467 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1468 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1473 redef fun calloc_array
(ret_type
, arguments
)
1475 var mclass
= self.get_class
("ArrayCapable")
1476 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1477 var res
= self.native_array_instance
(ft
, arguments
[1])
1481 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1482 assert mtype
.need_anchor
1483 var compiler
= self.compiler
1484 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1485 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1487 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1491 redef class MMethodDef
1492 fun separate_runtime_function
: AbstractRuntimeFunction
1494 var res
= self.separate_runtime_function_cache
1496 res
= new SeparateRuntimeFunction(self)
1497 self.separate_runtime_function_cache
= res
1501 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1503 fun virtual_runtime_function
: AbstractRuntimeFunction
1505 var res
= self.virtual_runtime_function_cache
1507 res
= new VirtualRuntimeFunction(self)
1508 self.virtual_runtime_function_cache
= res
1512 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1515 # The C function associated to a methoddef separately compiled
1516 class SeparateRuntimeFunction
1517 super AbstractRuntimeFunction
1519 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1521 redef fun to_s
do return self.mmethoddef
.to_s
1523 redef fun compile_to_c
(compiler
)
1525 var mmethoddef
= self.mmethoddef
1527 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1528 var v
= compiler
.new_visitor
1529 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1530 var arguments
= new Array[RuntimeVariable]
1531 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1534 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1536 var sig
= new Buffer
1537 var comment
= new Buffer
1538 var ret
= msignature
.return_mtype
1540 sig
.append
("{ret.ctype} ")
1541 else if mmethoddef
.mproperty
.is_new
then
1543 sig
.append
("{ret.ctype} ")
1547 sig
.append
(self.c_name
)
1548 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1549 comment
.append
("({selfvar}: {selfvar.mtype}")
1550 arguments
.add
(selfvar
)
1551 for i
in [0..msignature
.arity
[ do
1552 var mtype
= msignature
.mparameters
[i
].mtype
1553 if i
== msignature
.vararg_rank
then
1554 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1556 comment
.append
(", {mtype}")
1557 sig
.append
(", {mtype.ctype} p{i}")
1558 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1559 arguments
.add
(argvar
)
1564 comment
.append
(": {ret}")
1566 compiler
.provide_declaration
(self.c_name
, "{sig};")
1568 v
.add_decl
("/* method {self} for {comment} */")
1569 v
.add_decl
("{sig} \{")
1571 frame
.returnvar
= v
.new_var
(ret
)
1573 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1575 if recv
!= arguments
.first
.mtype
then
1576 #print "{self} {recv} {arguments.first}"
1578 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1580 v
.add
("{frame.returnlabel.as(not null)}:;")
1582 v
.add
("return {frame.returnvar.as(not null)};")
1588 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1589 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1590 class VirtualRuntimeFunction
1591 super AbstractRuntimeFunction
1593 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1595 redef fun to_s
do return self.mmethoddef
.to_s
1597 redef fun compile_to_c
(compiler
)
1599 var mmethoddef
= self.mmethoddef
1601 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1602 var v
= compiler
.new_visitor
1603 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1604 var arguments
= new Array[RuntimeVariable]
1605 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1608 var sig
= new Buffer
1609 var comment
= new Buffer
1611 # Because the function is virtual, the signature must match the one of the original class
1612 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1613 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1614 var ret
= msignature
.return_mtype
1616 sig
.append
("{ret.ctype} ")
1617 else if mmethoddef
.mproperty
.is_new
then
1619 sig
.append
("{ret.ctype} ")
1623 sig
.append
(self.c_name
)
1624 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1625 comment
.append
("({selfvar}: {selfvar.mtype}")
1626 arguments
.add
(selfvar
)
1627 for i
in [0..msignature
.arity
[ do
1628 var mtype
= msignature
.mparameters
[i
].mtype
1629 if i
== msignature
.vararg_rank
then
1630 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1632 comment
.append
(", {mtype}")
1633 sig
.append
(", {mtype.ctype} p{i}")
1634 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1635 arguments
.add
(argvar
)
1640 comment
.append
(": {ret}")
1642 compiler
.provide_declaration
(self.c_name
, "{sig};")
1644 v
.add_decl
("/* method {self} for {comment} */")
1645 v
.add_decl
("{sig} \{")
1647 frame
.returnvar
= v
.new_var
(ret
)
1649 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1651 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1653 assert subret
!= null
1654 v
.assign
(frame
.returnvar
.as(not null), subret
)
1657 v
.add
("{frame.returnlabel.as(not null)}:;")
1659 v
.add
("return {frame.returnvar.as(not null)};")
1665 redef fun call
(v
, arguments
) do abort
1669 fun const_color
: String do return "COLOR_{c_name}"
1672 redef class MProperty
1673 fun const_color
: String do return "COLOR_{c_name}"