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
101 # The result of the RTA (used to know live types and methods)
102 var runtime_type_analysis
: RapidTypeAnalysis
104 private var undead_types
: Set[MType] = new HashSet[MType]
105 private var partial_types
: Set[MType] = new HashSet[MType]
107 private var type_layout_builder
: TypingLayoutBuilder[MType]
108 private var type_layout
: nullable TypingLayout[MType]
109 private var type_tables
: nullable Map[MType, Array[nullable MType]] = null
111 private var live_unanchored_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
113 private var resolution_layout
: nullable ResolutionLayout
114 private var resolution_tables
: nullable Map[MClassType, Array[nullable MType]]
116 protected var method_layout
: nullable PropertyLayout[MMethod]
117 protected var method_tables
: Map[MClass, Array[nullable MPropDef]]
119 protected var attr_layout
: nullable PropertyLayout[MAttribute]
120 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]]
122 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis) do
124 self.header
= new_visitor
125 self.init_layout_builders
126 self.runtime_type_analysis
= runtime_type_analysis
127 self.do_property_coloring
128 self.compile_box_kinds
131 protected fun init_layout_builders
do
133 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
134 self.type_layout_builder
= new BMTypeLayoutBuilder(self.mainmodule
)
135 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
136 self.type_layout_builder
= new PHTypeLayoutBuilder(self.mainmodule
, new PHModOperator)
137 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
138 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
139 self.type_layout_builder
= new PHTypeLayoutBuilder(self.mainmodule
, new PHAndOperator)
140 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
142 self.type_layout_builder
= new CLTypeLayoutBuilder(self.mainmodule
)
146 redef fun compile_header_structs
do
147 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
148 self.compile_header_attribute_structs
149 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
151 # With unanchored_table, all live type resolution are stored in a big table: unanchored_table
152 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. */")
154 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
155 self.header
.add_decl
("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
157 self.header
.add_decl
("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unanchored lists). */")
160 self.header
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
163 fun compile_header_attribute_structs
165 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
166 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
168 self.header
.add_decl
("typedef union \{")
169 self.header
.add_decl
("void* val;")
170 for c
, v
in self.box_kinds
do
171 var t
= c
.mclass_type
172 self.header
.add_decl
("{t.ctype} {t.ctypename};")
174 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
178 fun compile_box_kinds
180 # Collect all bas box class
181 # FIXME: this is not completely fine with a separate compilation scheme
182 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
183 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
184 if classes
== null then continue
185 assert classes
.length
== 1 else print classes
.join
(", ")
186 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
190 var box_kinds
= new HashMap[MClass, Int]
192 fun box_kind_of
(mclass
: MClass): Int
194 if mclass
.mclass_type
.ctype
== "val*" then
196 else if mclass
.kind
== extern_kind
then
197 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
199 return self.box_kinds
[mclass
]
204 fun compile_color_consts
(colors
: Map[Object, Int]) do
205 for m
, c
in colors
do
206 if color_consts_done
.has
(m
) then continue
207 if m
isa MProperty then
208 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
209 self.header
.add_decl
("#define {m.const_color} {c}")
211 self.header
.add_decl
("extern const int {m.const_color};")
212 self.header
.add
("const int {m.const_color} = {c};")
214 else if m
isa MType then
215 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
216 self.header
.add_decl
("#define {m.const_color} {c}")
218 self.header
.add_decl
("extern const int {m.const_color};")
219 self.header
.add
("const int {m.const_color} = {c};")
222 color_consts_done
.add
(m
)
226 private var color_consts_done
= new HashSet[Object]
228 # colorize classe properties
229 fun do_property_coloring
do
230 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
233 var method_coloring
= new CLPropertyLayoutBuilder[MMethod](mainmodule
)
234 var method_layout
= method_coloring
.build_layout
(mclasses
)
235 self.method_tables
= build_method_tables
(mclasses
, method_layout
)
236 self.compile_color_consts
(method_layout
.pos
)
237 self.method_layout
= method_layout
239 # attributes coloration
240 var attribute_coloring
= new CLPropertyLayoutBuilder[MAttribute](mainmodule
)
241 var attr_layout
= attribute_coloring
.build_layout
(mclasses
)
242 self.attr_tables
= build_attr_tables
(mclasses
, attr_layout
)
243 self.compile_color_consts
(attr_layout
.pos
)
244 self.attr_layout
= attr_layout
247 fun build_method_tables
(mclasses
: Set[MClass], layout
: PropertyLayout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
248 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
249 for mclass
in mclasses
do
250 var table
= new Array[nullable MPropDef]
251 # first, fill table from parents by reverse linearization order
252 var parents
= self.mainmodule
.super_mclasses
(mclass
)
253 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
255 for mproperty
in self.mainmodule
.properties
(parent
) do
256 if not mproperty
isa MMethod then continue
257 var color
= layout
.pos
[mproperty
]
258 if table
.length
<= color
then
259 for i
in [table
.length
.. color
[ do
263 for mpropdef
in mproperty
.mpropdefs
do
264 if mpropdef
.mclassdef
.mclass
== parent
then
265 table
[color
] = mpropdef
271 # then override with local properties
272 for mproperty
in self.mainmodule
.properties
(mclass
) do
273 if not mproperty
isa MMethod then continue
274 var color
= layout
.pos
[mproperty
]
275 if table
.length
<= color
then
276 for i
in [table
.length
.. color
[ do
280 for mpropdef
in mproperty
.mpropdefs
do
281 if mpropdef
.mclassdef
.mclass
== mclass
then
282 table
[color
] = mpropdef
286 tables
[mclass
] = table
291 fun build_attr_tables
(mclasses
: Set[MClass], layout
: PropertyLayout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
292 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
293 for mclass
in mclasses
do
294 var table
= new Array[nullable MPropDef]
295 # first, fill table from parents by reverse linearization order
296 var parents
= self.mainmodule
.super_mclasses
(mclass
)
297 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
299 for mproperty
in self.mainmodule
.properties
(parent
) do
300 if not mproperty
isa MAttribute then continue
301 var color
= layout
.pos
[mproperty
]
302 if table
.length
<= color
then
303 for i
in [table
.length
.. color
[ do
307 for mpropdef
in mproperty
.mpropdefs
do
308 if mpropdef
.mclassdef
.mclass
== parent
then
309 table
[color
] = mpropdef
315 # then override with local properties
316 for mproperty
in self.mainmodule
.properties
(mclass
) do
317 if not mproperty
isa MAttribute then continue
318 var color
= layout
.pos
[mproperty
]
319 if table
.length
<= color
then
320 for i
in [table
.length
.. color
[ do
324 for mpropdef
in mproperty
.mpropdefs
do
325 if mpropdef
.mclassdef
.mclass
== mclass
then
326 table
[color
] = mpropdef
330 tables
[mclass
] = table
335 # colorize live types of the program
336 private fun do_type_coloring
: Set[MType] do
337 var mtypes
= new HashSet[MType]
338 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
339 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
340 mtypes
.add_all
(self.undead_types
)
341 for c
in self.box_kinds
.keys
do
342 mtypes
.add
(c
.mclass_type
)
345 for mtype
in mtypes
do
346 retieve_live_partial_types
(mtype
)
348 mtypes
.add_all
(self.partial_types
)
351 self.type_layout
= self.type_layout_builder
.build_layout
(mtypes
)
352 self.type_tables
= self.build_type_tables
(mtypes
)
354 # VT and FT are stored with other unresolved types in the big unanchored_tables
355 self.compile_unanchored_tables
(mtypes
)
361 fun build_type_tables
(mtypes
: Set[MType]): Map[MType, Array[nullable MType]] do
362 var tables
= new HashMap[MType, Array[nullable MType]]
363 var layout
= self.type_layout
364 for mtype
in mtypes
do
365 var table
= new Array[nullable MType]
366 var supers
= new HashSet[MType]
367 supers
.add_all
(self.mainmodule
.super_mtypes
(mtype
, mtypes
))
371 if layout
isa PHTypingLayout[MType] then
372 color
= layout
.hashes
[mtype
][sup
]
374 color
= layout
.pos
[sup
]
376 if table
.length
<= color
then
377 for i
in [table
.length
.. color
[ do
383 tables
[mtype
] = table
388 protected fun compile_unanchored_tables
(mtypes
: Set[MType]) do
389 # Unanchored_tables is used to perform a type resolution at runtime in O(1)
391 # During the visit of the body of classes, live_unanchored_types are collected
393 # Collect all live_unanchored_types (visited in the body of classes)
395 # Determinate fo each livetype what are its possible requested anchored types
396 var mtype2unanchored
= new HashMap[MClassType, Set[MType]]
397 for mtype
in self.runtime_type_analysis
.live_types
do
398 var set
= new HashSet[MType]
399 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
400 if self.live_unanchored_types
.has_key
(cd
) then
401 set
.add_all
(self.live_unanchored_types
[cd
])
404 mtype2unanchored
[mtype
] = set
407 # Compute the table layout with the prefered method
408 var resolution_builder
: ResolutionLayoutBuilder
409 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
410 resolution_builder
= new BMResolutionLayoutBuilder
411 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
412 resolution_builder
= new PHResolutionLayoutBuilder(new PHModOperator)
413 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
414 resolution_builder
= new PHResolutionLayoutBuilder(new PHAndOperator)
416 resolution_builder
= new CLResolutionLayoutBuilder
418 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unanchored
)
419 self.resolution_tables
= self.build_resolution_tables
(mtype2unanchored
)
421 # Compile a C constant for each collected unanchored type.
422 # Either to a color, or to -1 if the unanchored type is dead (no live receiver can require it)
423 var all_unanchored
= new HashSet[MType]
424 for t
in self.live_unanchored_types
.values
do
425 all_unanchored
.add_all
(t
)
427 var all_unanchored_types_colors
= new HashMap[MType, Int]
428 for t
in all_unanchored
do
429 if self.resolution_layout
.pos
.has_key
(t
) then
430 all_unanchored_types_colors
[t
] = self.resolution_layout
.pos
[t
]
432 all_unanchored_types_colors
[t
] = -1
435 self.compile_color_consts
(all_unanchored_types_colors
)
438 #for k, v in unanchored_types_tables.as(not null) do
439 # print "{k}: {v.join(", ")}"
444 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
445 var tables
= new HashMap[MClassType, Array[nullable MType]]
446 var layout
= self.resolution_layout
447 for mclasstype
, mtypes
in elements
do
448 var table
= new Array[nullable MType]
449 for mtype
in mtypes
do
451 if layout
isa PHResolutionLayout then
452 color
= layout
.hashes
[mclasstype
][mtype
]
454 color
= layout
.pos
[mtype
]
456 if table
.length
<= color
then
457 for i
in [table
.length
.. color
[ do
463 tables
[mclasstype
] = table
468 fun retieve_live_partial_types
(mtype
: MType) do
469 # add formal types arguments to mtypes
470 if mtype
isa MGenericType then
471 for ft
in mtype
.arguments
do
472 if ft
.need_anchor
then
473 print
("Why do we need anchor here ?")
476 self.partial_types
.add
(ft
)
477 retieve_live_partial_types
(ft
)
480 var mclass_type
: MClassType
481 if mtype
isa MNullableType then
482 mclass_type
= mtype
.mtype
.as(MClassType)
484 mclass_type
= mtype
.as(MClassType)
487 # add virtual types to mtypes
488 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
489 if vt
isa MVirtualTypeProp then
490 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
491 self.partial_types
.add
(anchored
)
496 # Separately compile all the method definitions of the module
497 fun compile_module_to_c
(mmodule
: MModule)
499 var old_module
= self.mainmodule
500 self.mainmodule
= mmodule
501 for cd
in mmodule
.mclassdefs
do
502 for pd
in cd
.mpropdefs
do
503 if not pd
isa MMethodDef then continue
504 #print "compile {pd} @ {cd} @ {mmodule}"
505 var r
= new SeparateRuntimeFunction(pd
)
507 if true or cd
.bound_mtype
.ctype
!= "val*" then
508 var r2
= new VirtualRuntimeFunction(pd
)
509 r2
.compile_to_c
(self)
513 self.mainmodule
= old_module
516 # Globaly compile the type structure of a live type
517 fun compile_type_to_c
(mtype
: MType)
519 var c_name
= mtype
.c_name
520 var v
= new SeparateCompilerVisitor(self)
521 v
.add_decl
("/* runtime type {mtype} */")
523 # extern const struct type_X
524 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
525 self.header
.add_decl
("struct type_{c_name} \{")
526 self.header
.add_decl
("int id;")
527 self.header
.add_decl
("const char *name;")
528 self.header
.add_decl
("int color;")
529 self.header
.add_decl
("short int is_nullable;")
530 self.header
.add_decl
("const struct types *unanchored_table;")
531 self.header
.add_decl
("int table_size;")
532 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
533 self.header
.add_decl
("\};")
535 # const struct type_X
536 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
537 v
.add_decl
("{self.type_layout.ids[mtype]},")
538 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
539 var layout
= self.type_layout
540 if layout
isa PHTypingLayout[MType] then
541 v
.add_decl
("{layout.masks[mtype]},")
543 v
.add_decl
("{layout.pos[mtype]},")
545 if mtype
isa MNullableType then
550 if compile_type_unanchored_table
(mtype
) then
551 v
.add_decl
("(struct types*) &unanchored_table_{c_name},")
555 v
.add_decl
("{self.type_tables[mtype].length},")
557 for stype
in self.type_tables
[mtype
] do
558 if stype
== null then
559 v
.add_decl
("-1, /* empty */")
561 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
568 fun compile_type_unanchored_table
(mtype
: MType): Bool do
570 var mclass_type
: MClassType
571 if mtype
isa MNullableType then
572 mclass_type
= mtype
.mtype
.as(MClassType)
574 mclass_type
= mtype
.as(MClassType)
576 if not self.resolution_tables
.has_key
(mclass_type
) then return false
578 var layout
= self.resolution_layout
580 # extern const struct unanchored_table_X unanchored_table_X
581 self.header
.add_decl
("extern const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name};")
582 self.header
.add_decl
("struct unanchored_table_{mtype.c_name} \{")
583 if layout
isa PHResolutionLayout then
584 self.header
.add_decl
("int mask;")
586 self.header
.add_decl
("struct type *types[{self.resolution_tables[mclass_type].length}];")
587 self.header
.add_decl
("\};")
589 # const struct fts_table_X fts_table_X
591 v
.add_decl
("const struct unanchored_table_{mtype.c_name} unanchored_table_{mtype.c_name} = \{")
592 if layout
isa PHResolutionLayout then
593 v
.add_decl
("{layout.masks[mclass_type]},")
596 for t
in self.resolution_tables
[mclass_type
] do
598 v
.add_decl
("NULL, /* empty */")
600 # The table stores the result of the type resolution
601 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
602 # the value stored is tv.
603 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
604 # FIXME: What typeids means here? How can a tv not be live?
605 if self.type_layout
.ids
.has_key
(tv
) then
606 v
.add_decl
("(struct type*)&type_{tv.c_name}, /* {t}: {tv} */")
608 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
617 # Globally compile the table of the class mclass
618 # In a link-time optimisation compiler, tables are globally computed
619 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
620 fun compile_class_to_c
(mclass
: MClass)
622 var mtype
= mclass
.intro
.bound_mtype
623 var c_name
= mclass
.c_name
625 var vft
= self.method_tables
[mclass
]
626 var attrs
= self.attr_tables
[mclass
]
629 v
.add_decl
("/* runtime class {c_name} */")
631 self.header
.add_decl
("struct class_{c_name} \{")
632 self.header
.add_decl
("int box_kind;")
633 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
634 self.header
.add_decl
("\};")
637 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
638 v
.add_decl
("const struct class_{c_name} 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 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
647 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
649 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
656 if mtype
.ctype
!= "val*" then
657 #Build instance struct
658 self.header
.add_decl
("struct instance_{c_name} \{")
659 self.header
.add_decl
("const struct type *type;")
660 self.header
.add_decl
("const struct class *class;")
661 self.header
.add_decl
("{mtype.ctype} value;")
662 self.header
.add_decl
("\};")
664 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 = GC_MALLOC(sizeof(struct instance_{c_name}));")
670 v
.add
("res->type = (struct type*) &type_{c_name};")
671 v
.add
("res->class = (struct class*) &class_{c_name};")
672 v
.add
("res->value = value;")
673 v
.add
("return (val*)res;")
678 var is_native_array
= mclass
.name
== "NativeArray"
681 if is_native_array
then
682 sig
= "int length, struct type* type"
684 sig
= "struct type* type"
687 #Build instance struct
688 #extern const struct instance_array__NativeArray instance_array__NativeArray;
689 self.header
.add_decl
("struct instance_{c_name} \{")
690 self.header
.add_decl
("const struct type *type;")
691 self.header
.add_decl
("const struct class *class;")
692 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
693 if is_native_array
then
694 # NativeArrays are just a instance header followed by an array of values
695 self.header
.add_decl
("val* values[0];")
697 self.header
.add_decl
("\};")
700 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
701 v
.add_decl
("/* allocate {mtype} */")
702 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
703 var res
= v
.new_named_var
(mtype
, "self")
705 if is_native_array
then
706 var mtype_elt
= mtype
.arguments
.first
707 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
709 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
711 v
.add
("{res}->type = type;")
712 if v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then
713 v
.add
("if(type == NULL) \{")
714 v
.add_abort
("type null")
716 v
.add
("if(type->unanchored_table == NULL) \{")
717 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", type->name);")
718 v
.add_abort
("type dead")
721 v
.add
("{res}->class = (struct class*) &class_{c_name};")
723 self.generate_init_attr
(v
, res
, mtype
)
724 v
.add
("return {res};")
727 generate_check_init_instance
(mtype
)
730 redef fun generate_check_init_instance
(mtype
)
732 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
734 var v
= self.new_visitor
735 var c_name
= mtype
.mclass
.c_name
736 var res
= new RuntimeVariable("self", mtype
, mtype
)
737 self.header
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype});")
738 v
.add_decl
("/* allocate {mtype} */")
739 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
740 self.generate_check_attr
(v
, res
, mtype
)
744 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
748 redef fun display_stats
751 if self.modelbuilder
.toolcontext
.opt_typing_table_metrics
.value
then
758 print
"# size of tables"
759 print
"\trs size\trs hole\tst size\tst hole"
764 var rtables
= resolution_tables
765 if rtables
!= null then
766 for unanch
, table
in rtables
do
767 rt_table
+= table
.length
768 for e
in table
do if e
== null then rt_holes
+= 1
772 var ttables
= type_tables
773 if ttables
!= null then
774 for t
, table
in ttables
do
775 st_table
+= table
.length
776 for e
in table
do if e
== null then st_holes
+= 1
779 print
"\t{rt_table}\t{rt_holes}\t{st_table}\t{st_holes}"
783 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
784 class SeparateCompilerVisitor
785 super AbstractCompilerVisitor
787 redef type COMPILER: SeparateCompiler
789 redef fun adapt_signature
(m
, args
)
791 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
792 var recv
= args
.first
793 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
794 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
796 for i
in [0..msignature
.arity
[ do
797 var t
= msignature
.mparameters
[i
].mtype
798 if i
== msignature
.vararg_rank
then
801 args
[i
+1] = self.autobox
(args
[i
+1], t
)
805 redef fun autobox
(value
, mtype
)
807 if value
.mtype
== mtype
then
809 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
811 else if value
.mtype
.ctype
== "val*" then
812 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
813 else if mtype
.ctype
== "val*" then
814 var valtype
= value
.mtype
.as(MClassType)
815 var res
= self.new_var
(mtype
)
816 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
817 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
818 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
821 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
824 # Bad things will appen!
825 var res
= self.new_var
(mtype
)
826 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
827 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
832 # Return a C expression returning the runtime type structure of the value
833 # The point of the method is to works also with primitives types.
834 fun type_info
(value
: RuntimeVariable): String
836 if value
.mtype
.ctype
== "val*" then
837 return "{value}->type"
839 return "(&type_{value.mtype.c_name})"
843 redef fun send
(mmethod
, arguments
)
845 if arguments
.first
.mcasttype
.ctype
!= "val*" then
846 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
849 var res
: nullable RuntimeVariable
850 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
851 var ret
= msignature
.return_mtype
852 if mmethod
.is_new
then
853 ret
= arguments
.first
.mtype
854 res
= self.new_var
(ret
)
855 else if ret
== null then
858 res
= self.new_var
(ret
)
864 var recv
= arguments
.first
867 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
868 for i
in [0..msignature
.arity
[ do
869 var a
= arguments
[i
+1]
870 var t
= msignature
.mparameters
[i
].mtype
871 if i
== msignature
.vararg_rank
then
872 t
= arguments
[i
+1].mcasttype
874 s
.append
(", {t.ctype}")
875 a
= self.autobox
(a
, t
)
879 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
880 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
882 self.add
("if ({recv} == NULL) \{")
883 if mmethod
.name
== "==" then
885 var arg
= arguments
[1]
886 if arg
.mcasttype
isa MNullableType then
887 self.add
("{res} = ({arg} == NULL);")
888 else if arg
.mcasttype
isa MNullType then
889 self.add
("{res} = 1; /* is null */")
891 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
893 else if mmethod
.name
== "!=" then
895 var arg
= arguments
[1]
896 if arg
.mcasttype
isa MNullableType then
897 self.add
("{res} = ({arg} != NULL);")
898 else if arg
.mcasttype
isa MNullType then
899 self.add
("{res} = 0; /* is null */")
901 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
904 self.add_abort
("Reciever is null")
906 self.add
("\} else \{")
908 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
910 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
911 var arg
= arguments
[1]
912 if arg
.mcasttype
isa MNullType then
913 if mmethod
.name
== "==" then
914 self.add
("{res} = 0; /* arg is null but recv is not */")
916 self.add
("{res} = 1; /* arg is null and recv is not */")
926 if ret
== null then r
= "void" else r
= ret
.ctype
927 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
930 self.add
("{res} = {call};")
942 redef fun call
(mmethoddef
, recvtype
, arguments
)
944 var res
: nullable RuntimeVariable
945 var ret
= mmethoddef
.msignature
.return_mtype
946 if mmethoddef
.mproperty
.is_new
then
947 ret
= arguments
.first
.mtype
948 res
= self.new_var
(ret
)
949 else if ret
== null then
952 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
953 res
= self.new_var
(ret
)
956 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
957 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
958 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
959 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
960 frame
.returnlabel
= self.get_name
("RET_LABEL")
961 frame
.returnvar
= res
962 var old_frame
= self.frame
964 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
965 mmethoddef
.compile_inside_to_c
(self, arguments
)
966 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
968 self.frame
= old_frame
973 self.adapt_signature
(mmethoddef
, arguments
)
976 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
979 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
985 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
987 # A vararg must be stored into an new array
988 # The trick is that the dymaic type of the array may depends on the receiver
989 # of the method (ie recv) if the static type is unresolved
990 # This is more complex than usual because the unanchored type must not be resolved
991 # with the current receiver (ie self).
992 # Therefore to isolate the resolution from self, a local Frame is created.
993 # One can see this implementation as an inlined method of the receiver whose only
994 # job is to allocate the array
995 var old_frame
= self.frame
996 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
998 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
999 var res
= self.array_instance
(varargs
, elttype
)
1000 self.frame
= old_frame
1004 redef fun isset_attribute
(a
, recv
)
1006 self.check_recv_notnull
(recv
)
1007 var res
= self.new_var
(bool_type
)
1009 # What is the declared type of the attribute?
1010 var mtype
= a
.intro
.static_mtype
.as(not null)
1011 var intromclassdef
= a
.intro
.mclassdef
1012 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1014 if mtype
isa MNullableType then
1015 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1019 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1020 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1023 if mtype
.ctype
== "val*" then
1024 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1026 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1032 redef fun read_attribute
(a
, recv
)
1034 self.check_recv_notnull
(recv
)
1036 # What is the declared type of the attribute?
1037 var ret
= a
.intro
.static_mtype
.as(not null)
1038 var intromclassdef
= a
.intro
.mclassdef
1039 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1041 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1042 # Get the attribute or a box (ie. always a val*)
1043 var cret
= self.object_type
.as_nullable
1044 var res
= self.new_var
(cret
)
1047 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1049 # Check for Uninitialized attribute
1050 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1051 self.add
("if ({res} == NULL) \{")
1052 self.add_abort
("Uninitialized attribute {a.name}")
1056 # Return the attribute or its unboxed version
1057 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1058 return self.autobox
(res
, ret
)
1060 var res
= self.new_var
(ret
)
1061 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1063 # Check for Uninitialized attribute
1064 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1065 self.add
("if ({res} == NULL) \{")
1066 self.add_abort
("Uninitialized attribute {a.name}")
1074 redef fun write_attribute
(a
, recv
, value
)
1076 self.check_recv_notnull
(recv
)
1078 # What is the declared type of the attribute?
1079 var mtype
= a
.intro
.static_mtype
.as(not null)
1080 var intromclassdef
= a
.intro
.mclassdef
1081 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1083 # Adapt the value to the declared type
1084 value
= self.autobox
(value
, mtype
)
1086 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1087 var attr
= "{recv}->attrs[{a.const_color}]"
1088 if mtype
.ctype
!= "val*" then
1089 assert mtype
isa MClassType
1090 # The attribute is primitive, thus we store it in a box
1091 # The trick is to create the box the first time then resuse the box
1092 self.add
("if ({attr} != NULL) \{")
1093 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1094 self.add
("\} else \{")
1095 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1096 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1099 # The attribute is not primitive, thus store it direclty
1100 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1103 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1107 redef fun init_instance
(mtype
)
1109 var compiler
= self.compiler
1110 if mtype
isa MGenericType and mtype
.need_anchor
then
1111 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1112 var recv
= self.frame
.arguments
.first
1113 var recv_type_info
= self.type_info
(recv
)
1114 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1115 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
)
1117 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1120 compiler
.undead_types
.add
(mtype
)
1121 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
1124 redef fun check_init_instance
(value
, mtype
)
1126 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1127 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1130 redef fun type_test
(value
, mtype
, tag
)
1132 self.add
("/* {value.inspect} isa {mtype} */")
1133 var compiler
= self.compiler
1135 var recv
= self.frame
.arguments
.first
1136 var recv_type_info
= self.type_info
(recv
)
1138 var res
= self.new_var
(bool_type
)
1140 var cltype
= self.get_name
("cltype")
1141 self.add_decl
("int {cltype};")
1142 var idtype
= self.get_name
("idtype")
1143 self.add_decl
("int {idtype};")
1145 var maybe_null
= self.maybe_null
(value
)
1146 var accept_null
= "0"
1148 if ntype
isa MNullableType then
1153 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1154 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1155 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1156 self.compiler
.count_type_test_skipped
[tag
] += 1
1157 self.add
("count_type_test_skipped_{tag}++;")
1162 if ntype
.need_anchor
then
1163 var type_struct
= self.get_name
("type_struct")
1164 self.add_decl
("struct type* {type_struct};")
1166 # Either with unanchored_table with a direct resolution
1167 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1168 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1169 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[HASH({recv_type_info}->unanchored_table->mask, {ntype.const_color})];")
1171 self.add
("{type_struct} = {recv_type_info}->unanchored_table->types[{ntype.const_color}];")
1173 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1174 self.compiler
.count_type_test_unresolved
[tag
] += 1
1175 self.add
("count_type_test_unresolved_{tag}++;")
1177 self.add
("{cltype} = {type_struct}->color;")
1178 self.add
("{idtype} = {type_struct}->id;")
1179 if maybe_null
and accept_null
== "0" then
1180 var is_nullable
= self.get_name
("is_nullable")
1181 self.add_decl
("short int {is_nullable};")
1182 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1183 accept_null
= is_nullable
.to_s
1185 else if ntype
isa MClassType then
1186 compiler
.undead_types
.add
(mtype
)
1187 self.add
("{cltype} = type_{mtype.c_name}.color;")
1188 self.add
("{idtype} = type_{mtype.c_name}.id;")
1189 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1190 self.compiler
.count_type_test_resolved
[tag
] += 1
1191 self.add
("count_type_test_resolved_{tag}++;")
1194 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1197 # check color is in table
1199 self.add
("if({value} == NULL) \{")
1200 self.add
("{res} = {accept_null};")
1201 self.add
("\} else \{")
1203 var value_type_info
= self.type_info
(value
)
1204 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1205 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1207 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1208 self.add
("{res} = 0;")
1209 self.add
("\} else \{")
1210 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1219 redef fun is_same_type_test
(value1
, value2
)
1221 var res
= self.new_var
(bool_type
)
1222 # Swap values to be symetric
1223 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1228 if value1
.mtype
.ctype
!= "val*" then
1229 if value2
.mtype
== value1
.mtype
then
1230 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1231 else if value2
.mtype
.ctype
!= "val*" then
1232 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1234 var mtype1
= value1
.mtype
.as(MClassType)
1235 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1238 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1243 redef fun class_name_string
(value
)
1245 var res
= self.get_name
("var_class_name")
1246 self.add_decl
("const char* {res};")
1247 if value
.mtype
.ctype
== "val*" then
1248 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1250 self.add
"{res} = type_{value.mtype.c_name}.name;"
1255 redef fun equal_test
(value1
, value2
)
1257 var res
= self.new_var
(bool_type
)
1258 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1263 if value1
.mtype
.ctype
!= "val*" then
1264 if value2
.mtype
== value1
.mtype
then
1265 self.add
("{res} = {value1} == {value2};")
1266 else if value2
.mtype
.ctype
!= "val*" then
1267 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1269 var mtype1
= value1
.mtype
.as(MClassType)
1270 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1271 self.add
("if ({res}) \{")
1272 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1277 var maybe_null
= true
1278 var test
= new Array[String]
1279 var t1
= value1
.mcasttype
1280 if t1
isa MNullableType then
1281 test
.add
("{value1} != NULL")
1286 var t2
= value2
.mcasttype
1287 if t2
isa MNullableType then
1288 test
.add
("{value2} != NULL")
1294 var incompatible
= false
1296 if t1
.ctype
!= "val*" then
1299 # No need to compare class
1300 else if t2
.ctype
!= "val*" then
1302 else if can_be_primitive
(value2
) then
1303 test
.add
("{value1}->class == {value2}->class")
1307 else if t2
.ctype
!= "val*" then
1309 if can_be_primitive
(value1
) then
1310 test
.add
("{value1}->class == {value2}->class")
1318 if incompatible
then
1320 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1323 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1327 if primitive
!= null then
1328 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1329 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1330 test
.add
("{value1}->class == {value2}->class")
1331 var s
= new Array[String]
1332 for t
, v
in self.compiler
.box_kinds
do
1333 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1335 test
.add
("({s.join(" || ")})")
1337 self.add
("{res} = {value1} == {value2};")
1340 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1344 fun can_be_primitive
(value
: RuntimeVariable): Bool
1346 var t
= value
.mcasttype
1347 if t
isa MNullableType then t
= t
.mtype
1348 if not t
isa MClassType then return false
1349 var k
= t
.mclass
.kind
1350 return k
== interface_kind
or t
.ctype
!= "val*"
1353 fun maybe_null
(value
: RuntimeVariable): Bool
1355 var t
= value
.mcasttype
1356 return t
isa MNullableType or t
isa MNullType
1359 redef fun array_instance
(array
, elttype
)
1361 var nclass
= self.get_class
("NativeArray")
1362 var arrayclass
= self.get_class
("Array")
1363 var arraytype
= arrayclass
.get_mtype
([elttype
])
1364 var res
= self.init_instance
(arraytype
)
1365 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1366 var length
= self.int_instance
(array
.length
)
1367 var nat
= native_array_instance
(elttype
, length
)
1368 for i
in [0..array
.length
[ do
1369 var r
= self.autobox
(array
[i
], self.object_type
)
1370 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1372 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1373 self.check_init_instance
(res
, arraytype
)
1378 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1380 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1381 assert mtype
isa MGenericType
1382 var compiler
= self.compiler
1383 if mtype
.need_anchor
then
1384 link_unanchored_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1385 var recv
= self.frame
.arguments
.first
1386 var recv_type_info
= self.type_info
(recv
)
1387 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1388 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
)
1390 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->unanchored_table->types[{mtype.const_color}])", mtype
)
1393 compiler
.undead_types
.add
(mtype
)
1394 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype
)
1397 redef fun native_array_def
(pname
, ret_type
, arguments
)
1399 var elttype
= arguments
.first
.mtype
1400 var nclass
= self.get_class
("NativeArray")
1401 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1402 if pname
== "[]" then
1403 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1405 else if pname
== "[]=" then
1406 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1408 else if pname
== "copy_to" then
1409 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1410 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1415 redef fun calloc_array
(ret_type
, arguments
)
1417 var mclass
= self.get_class
("ArrayCapable")
1418 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1419 var res
= self.native_array_instance
(ft
, arguments
[1])
1423 fun link_unanchored_type
(mclassdef
: MClassDef, mtype
: MType) do
1424 assert mtype
.need_anchor
1425 var compiler
= self.compiler
1426 if not compiler
.live_unanchored_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1427 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1429 compiler
.live_unanchored_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1433 # The C function associated to a methoddef separately compiled
1434 class SeparateRuntimeFunction
1435 super AbstractRuntimeFunction
1437 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1439 redef fun to_s
do return self.mmethoddef
.to_s
1441 redef fun compile_to_c
(compiler
)
1443 var mmethoddef
= self.mmethoddef
1445 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1446 var v
= compiler
.new_visitor
1447 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1448 var arguments
= new Array[RuntimeVariable]
1449 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1452 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1454 var sig
= new Buffer
1455 var comment
= new Buffer
1456 var ret
= msignature
.return_mtype
1458 sig
.append
("{ret.ctype} ")
1459 else if mmethoddef
.mproperty
.is_new
then
1461 sig
.append
("{ret.ctype} ")
1465 sig
.append
(self.c_name
)
1466 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1467 comment
.append
("(self: {selfvar}")
1468 arguments
.add
(selfvar
)
1469 for i
in [0..msignature
.arity
[ do
1470 var mtype
= msignature
.mparameters
[i
].mtype
1471 if i
== msignature
.vararg_rank
then
1472 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1474 comment
.append
(", {mtype}")
1475 sig
.append
(", {mtype.ctype} p{i}")
1476 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1477 arguments
.add
(argvar
)
1482 comment
.append
(": {ret}")
1484 compiler
.header
.add_decl
("{sig};")
1486 v
.add_decl
("/* method {self} for {comment} */")
1487 v
.add_decl
("{sig} \{")
1489 frame
.returnvar
= v
.new_var
(ret
)
1491 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1493 if recv
!= arguments
.first
.mtype
then
1494 #print "{self} {recv} {arguments.first}"
1496 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1498 v
.add
("{frame.returnlabel.as(not null)}:;")
1500 v
.add
("return {frame.returnvar.as(not null)};")
1506 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1507 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1508 class VirtualRuntimeFunction
1509 super AbstractRuntimeFunction
1511 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1513 redef fun to_s
do return self.mmethoddef
.to_s
1515 redef fun compile_to_c
(compiler
)
1517 var mmethoddef
= self.mmethoddef
1519 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1520 var v
= compiler
.new_visitor
1521 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1522 var arguments
= new Array[RuntimeVariable]
1523 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1526 var sig
= new Buffer
1527 var comment
= new Buffer
1529 # Because the function is virtual, the signature must match the one of the original class
1530 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1531 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1532 var ret
= msignature
.return_mtype
1534 sig
.append
("{ret.ctype} ")
1535 else if mmethoddef
.mproperty
.is_new
then
1537 sig
.append
("{ret.ctype} ")
1541 sig
.append
(self.c_name
)
1542 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1543 comment
.append
("(self: {selfvar}")
1544 arguments
.add
(selfvar
)
1545 for i
in [0..msignature
.arity
[ do
1546 var mtype
= msignature
.mparameters
[i
].mtype
1547 if i
== msignature
.vararg_rank
then
1548 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1550 comment
.append
(", {mtype}")
1551 sig
.append
(", {mtype.ctype} p{i}")
1552 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1553 arguments
.add
(argvar
)
1558 comment
.append
(": {ret}")
1560 compiler
.header
.add_decl
("{sig};")
1562 v
.add_decl
("/* method {self} for {comment} */")
1563 v
.add_decl
("{sig} \{")
1565 frame
.returnvar
= v
.new_var
(ret
)
1567 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1569 if recv
!= arguments
.first
.mtype
then
1570 #print "{self} {recv} {arguments.first}"
1572 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1574 v
.add
("{frame.returnlabel.as(not null)}:;")
1576 v
.add
("return {frame.returnvar.as(not null)};")
1582 redef fun call
(v
, arguments
) do abort
1586 fun const_color
: String do return "COLOR_{c_name}"
1589 redef class MProperty
1590 fun const_color
: String do return "COLOR_{c_name}"