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
("*** 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]
106 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
108 private var type_layout
: nullable Layout[MType]
109 private var resolution_layout
: nullable Layout[MType]
110 protected var method_layout
: nullable Layout[MMethod]
111 protected var attr_layout
: nullable Layout[MAttribute]
113 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis) do
114 super(mainmodule
, mmbuilder
)
115 self.header
= new_visitor
116 self.runtime_type_analysis
= runtime_type_analysis
117 self.do_property_coloring
118 self.compile_box_kinds
121 redef fun compile_header_structs
do
122 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
123 self.compile_header_attribute_structs
124 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
126 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
127 self.header
.add_decl
("struct type \{ int id; const char *name; int color; short int is_nullable; struct types *resolution_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
129 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
130 self.header
.add_decl
("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unresolved lists). */")
132 self.header
.add_decl
("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unresolved lists). */")
135 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
136 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
137 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
138 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
141 self.header
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
144 fun compile_header_attribute_structs
146 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
147 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
149 self.header
.add_decl
("typedef union \{")
150 self.header
.add_decl
("void* val;")
151 for c
, v
in self.box_kinds
do
152 var t
= c
.mclass_type
153 self.header
.add_decl
("{t.ctype} {t.ctypename};")
155 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
159 fun compile_box_kinds
161 # Collect all bas box class
162 # FIXME: this is not completely fine with a separate compilation scheme
163 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
164 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
165 if classes
== null then continue
166 assert classes
.length
== 1 else print classes
.join
(", ")
167 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
171 var box_kinds
= new HashMap[MClass, Int]
173 fun box_kind_of
(mclass
: MClass): Int
175 if mclass
.mclass_type
.ctype
== "val*" then
177 else if mclass
.kind
== extern_kind
then
178 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
180 return self.box_kinds
[mclass
]
185 fun compile_color_consts
(colors
: Map[Object, Int]) do
186 for m
, c
in colors
do
187 if color_consts_done
.has
(m
) then continue
188 if m
isa MProperty then
189 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
190 self.header
.add_decl
("#define {m.const_color} {c}")
192 self.header
.add_decl
("extern const int {m.const_color};")
193 self.header
.add
("const int {m.const_color} = {c};")
195 else if m
isa MType then
196 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
197 self.header
.add_decl
("#define {m.const_color} {c}")
199 self.header
.add_decl
("extern const int {m.const_color};")
200 self.header
.add
("const int {m.const_color} = {c};")
203 color_consts_done
.add
(m
)
207 private var color_consts_done
= new HashSet[Object]
209 # colorize classe properties
210 fun do_property_coloring
do
211 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
214 var method_layout_builder
: PropertyLayoutBuilder[MMethod]
215 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
216 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
217 method_layout_builder
= new MMethodBMizer(self.mainmodule
)
218 attribute_layout_builder
= new MAttributeBMizer(self.mainmodule
)
220 method_layout_builder
= new MMethodColorer(self.mainmodule
)
221 attribute_layout_builder
= new MAttributeColorer(self.mainmodule
)
225 var method_layout
= method_layout_builder
.build_layout
(mclasses
)
226 self.method_tables
= build_method_tables
(mclasses
, method_layout
)
227 self.compile_color_consts
(method_layout
.pos
)
228 self.method_layout
= method_layout
230 # attributes coloration
231 var attr_layout
= attribute_layout_builder
.build_layout
(mclasses
)
232 self.attr_tables
= build_attr_tables
(mclasses
, attr_layout
)
233 self.compile_color_consts
(attr_layout
.pos
)
234 self.attr_layout
= attr_layout
237 fun build_method_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
238 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
239 for mclass
in mclasses
do
240 var table
= new Array[nullable MPropDef]
241 # first, fill table from parents by reverse linearization order
242 var parents
= self.mainmodule
.super_mclasses
(mclass
)
243 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
245 for mproperty
in self.mainmodule
.properties
(parent
) do
246 if not mproperty
isa MMethod then continue
247 var color
= layout
.pos
[mproperty
]
248 if table
.length
<= color
then
249 for i
in [table
.length
.. color
[ do
253 for mpropdef
in mproperty
.mpropdefs
do
254 if mpropdef
.mclassdef
.mclass
== parent
then
255 table
[color
] = mpropdef
261 # then override with local properties
262 for mproperty
in self.mainmodule
.properties
(mclass
) do
263 if not mproperty
isa MMethod then continue
264 var color
= layout
.pos
[mproperty
]
265 if table
.length
<= color
then
266 for i
in [table
.length
.. color
[ do
270 for mpropdef
in mproperty
.mpropdefs
do
271 if mpropdef
.mclassdef
.mclass
== mclass
then
272 table
[color
] = mpropdef
276 tables
[mclass
] = table
281 fun build_attr_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
282 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
283 for mclass
in mclasses
do
284 var table
= new Array[nullable MPropDef]
285 # first, fill table from parents by reverse linearization order
286 var parents
= self.mainmodule
.super_mclasses
(mclass
)
287 var lin
= self.mainmodule
.reverse_linearize_mclasses
(parents
)
289 for mproperty
in self.mainmodule
.properties
(parent
) do
290 if not mproperty
isa MAttribute then continue
291 var color
= layout
.pos
[mproperty
]
292 if table
.length
<= color
then
293 for i
in [table
.length
.. color
[ do
297 for mpropdef
in mproperty
.mpropdefs
do
298 if mpropdef
.mclassdef
.mclass
== parent
then
299 table
[color
] = mpropdef
305 # then override with local properties
306 for mproperty
in self.mainmodule
.properties
(mclass
) do
307 if not mproperty
isa MAttribute then continue
308 var color
= layout
.pos
[mproperty
]
309 if table
.length
<= color
then
310 for i
in [table
.length
.. color
[ do
314 for mpropdef
in mproperty
.mpropdefs
do
315 if mpropdef
.mclassdef
.mclass
== mclass
then
316 table
[color
] = mpropdef
320 tables
[mclass
] = table
325 # colorize live types of the program
326 private fun do_type_coloring
: Set[MType] do
327 var mtypes
= new HashSet[MType]
328 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
329 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
330 mtypes
.add_all
(self.undead_types
)
331 for c
in self.box_kinds
.keys
do
332 mtypes
.add
(c
.mclass_type
)
335 for mtype
in mtypes
do
336 retieve_live_partial_types
(mtype
)
338 mtypes
.add_all
(self.partial_types
)
341 var layout_builder
: TypingLayoutBuilder[MType]
342 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
343 layout_builder
= new MTypeBMizer(self.mainmodule
)
344 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
345 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
346 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
347 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
349 layout_builder
= new MTypeColorer(self.mainmodule
)
353 self.type_layout
= layout_builder
.build_layout
(mtypes
)
354 self.type_tables
= self.build_type_tables
(mtypes
)
356 # VT and FT are stored with other unresolved types in the big resolution_tables
357 self.compile_resolution_tables
(mtypes
)
363 fun build_type_tables
(mtypes
: Set[MType]): Map[MType, Array[nullable MType]] do
364 var tables
= new HashMap[MType, Array[nullable MType]]
365 var layout
= self.type_layout
366 for mtype
in mtypes
do
367 var table
= new Array[nullable MType]
368 var supers
= new HashSet[MType]
369 supers
.add_all
(self.mainmodule
.super_mtypes
(mtype
, mtypes
))
373 if layout
isa PHLayout[MType, MType] then
374 color
= layout
.hashes
[mtype
][sup
]
376 color
= layout
.pos
[sup
]
378 if table
.length
<= color
then
379 for i
in [table
.length
.. color
[ do
385 tables
[mtype
] = table
390 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
391 # resolution_tables is used to perform a type resolution at runtime in O(1)
393 # During the visit of the body of classes, live_unresolved_types are collected
395 # Collect all live_unresolved_types (visited in the body of classes)
397 # Determinate fo each livetype what are its possible requested anchored types
398 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
399 for mtype
in self.runtime_type_analysis
.live_types
do
400 var set
= new HashSet[MType]
401 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
402 if self.live_unresolved_types
.has_key
(cd
) then
403 set
.add_all
(self.live_unresolved_types
[cd
])
406 mtype2unresolved
[mtype
] = set
409 # Compute the table layout with the prefered method
410 var resolution_builder
: ResolutionLayoutBuilder
411 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
412 resolution_builder
= new ResolutionBMizer
413 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
414 resolution_builder
= new ResolutionHasher(new PHModOperator)
415 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
416 resolution_builder
= new ResolutionHasher(new PHAndOperator)
418 resolution_builder
= new ResolutionColorer
420 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
421 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
423 # Compile a C constant for each collected unresolved type.
424 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
425 var all_unresolved
= new HashSet[MType]
426 for t
in self.live_unresolved_types
.values
do
427 all_unresolved
.add_all
(t
)
429 var all_unresolved_types_colors
= new HashMap[MType, Int]
430 for t
in all_unresolved
do
431 if self.resolution_layout
.pos
.has_key
(t
) then
432 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
434 all_unresolved_types_colors
[t
] = -1
437 self.compile_color_consts
(all_unresolved_types_colors
)
440 #for k, v in unresolved_types_tables.as(not null) do
441 # print "{k}: {v.join(", ")}"
446 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
447 var tables
= new HashMap[MClassType, Array[nullable MType]]
448 var layout
= self.resolution_layout
449 for mclasstype
, mtypes
in elements
do
450 var table
= new Array[nullable MType]
451 for mtype
in mtypes
do
453 if layout
isa PHLayout[MClassType, MType] then
454 color
= layout
.hashes
[mclasstype
][mtype
]
456 color
= layout
.pos
[mtype
]
458 if table
.length
<= color
then
459 for i
in [table
.length
.. color
[ do
465 tables
[mclasstype
] = table
470 fun retieve_live_partial_types
(mtype
: MType) do
471 # add formal types arguments to mtypes
472 if mtype
isa MGenericType then
473 for ft
in mtype
.arguments
do
474 if ft
.need_anchor
then
475 print
("Why do we need anchor here ?")
478 self.partial_types
.add
(ft
)
479 retieve_live_partial_types
(ft
)
482 var mclass_type
: MClassType
483 if mtype
isa MNullableType then
484 mclass_type
= mtype
.mtype
.as(MClassType)
486 mclass_type
= mtype
.as(MClassType)
489 # add virtual types to mtypes
490 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
491 if vt
isa MVirtualTypeProp then
492 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
493 self.partial_types
.add
(anchored
)
498 # Separately compile all the method definitions of the module
499 fun compile_module_to_c
(mmodule
: MModule)
501 var old_module
= self.mainmodule
502 self.mainmodule
= mmodule
503 for cd
in mmodule
.mclassdefs
do
504 for pd
in cd
.mpropdefs
do
505 if not pd
isa MMethodDef then continue
506 #print "compile {pd} @ {cd} @ {mmodule}"
507 var r
= new SeparateRuntimeFunction(pd
)
509 if true or cd
.bound_mtype
.ctype
!= "val*" then
510 var r2
= new VirtualRuntimeFunction(pd
)
511 r2
.compile_to_c
(self)
515 self.mainmodule
= old_module
518 # Globaly compile the type structure of a live type
519 fun compile_type_to_c
(mtype
: MType)
521 var c_name
= mtype
.c_name
522 var v
= new SeparateCompilerVisitor(self)
523 v
.add_decl
("/* runtime type {mtype} */")
525 # extern const struct type_X
526 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
527 self.header
.add_decl
("struct type_{c_name} \{")
528 self.header
.add_decl
("int id;")
529 self.header
.add_decl
("const char *name;")
530 self.header
.add_decl
("int color;")
531 self.header
.add_decl
("short int is_nullable;")
532 self.header
.add_decl
("const struct types *resolution_table;")
533 self.header
.add_decl
("int table_size;")
534 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
535 self.header
.add_decl
("\};")
537 # const struct type_X
538 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
539 v
.add_decl
("{self.type_layout.ids[mtype]},")
540 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
541 var layout
= self.type_layout
542 if layout
isa PHLayout[MType, MType] then
543 v
.add_decl
("{layout.masks[mtype]},")
545 v
.add_decl
("{layout.pos[mtype]},")
547 if mtype
isa MNullableType then
552 if compile_type_resolution_table
(mtype
) then
553 v
.add_decl
("(struct types*) &resolution_table_{c_name},")
557 v
.add_decl
("{self.type_tables[mtype].length},")
559 for stype
in self.type_tables
[mtype
] do
560 if stype
== null then
561 v
.add_decl
("-1, /* empty */")
563 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
570 fun compile_type_resolution_table
(mtype
: MType): Bool do
572 var mclass_type
: MClassType
573 if mtype
isa MNullableType then
574 mclass_type
= mtype
.mtype
.as(MClassType)
576 mclass_type
= mtype
.as(MClassType)
578 if not self.resolution_tables
.has_key
(mclass_type
) then return false
580 var layout
= self.resolution_layout
582 # extern const struct resolution_table_X resolution_table_X
583 self.header
.add_decl
("extern const struct resolution_table_{mtype.c_name} resolution_table_{mtype.c_name};")
584 self.header
.add_decl
("struct resolution_table_{mtype.c_name} \{")
585 if layout
isa PHLayout[MClassType, MType] then
586 self.header
.add_decl
("int mask;")
588 self.header
.add_decl
("struct type *types[{self.resolution_tables[mclass_type].length}];")
589 self.header
.add_decl
("\};")
591 # const struct fts_table_X fts_table_X
593 v
.add_decl
("const struct resolution_table_{mtype.c_name} resolution_table_{mtype.c_name} = \{")
594 if layout
isa PHLayout[MClassType, MType] then
595 v
.add_decl
("{layout.masks[mclass_type]},")
598 for t
in self.resolution_tables
[mclass_type
] do
600 v
.add_decl
("NULL, /* empty */")
602 # The table stores the result of the type resolution
603 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
604 # the value stored is tv.
605 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
606 # FIXME: What typeids means here? How can a tv not be live?
607 if self.type_layout
.ids
.has_key
(tv
) then
608 v
.add_decl
("(struct type*)&type_{tv.c_name}, /* {t}: {tv} */")
610 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
619 # Globally compile the table of the class mclass
620 # In a link-time optimisation compiler, tables are globally computed
621 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
622 fun compile_class_to_c
(mclass
: MClass)
624 var mtype
= mclass
.intro
.bound_mtype
625 var c_name
= mclass
.c_name
627 var vft
= self.method_tables
[mclass
]
628 var attrs
= self.attr_tables
[mclass
]
631 v
.add_decl
("/* runtime class {c_name} */")
633 self.header
.add_decl
("struct class_{c_name} \{")
634 self.header
.add_decl
("int box_kind;")
635 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
636 self.header
.add_decl
("\};")
639 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
640 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
641 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
643 for i
in [0 .. vft
.length
[ do
644 var mpropdef
= vft
[i
]
645 if mpropdef
== null then
646 v
.add_decl
("NULL, /* empty */")
648 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
649 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
651 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
658 if mtype
.ctype
!= "val*" then
659 #Build instance struct
660 self.header
.add_decl
("struct instance_{c_name} \{")
661 self.header
.add_decl
("const struct type *type;")
662 self.header
.add_decl
("const struct class *class;")
663 self.header
.add_decl
("{mtype.ctype} value;")
664 self.header
.add_decl
("\};")
666 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
668 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
669 v
.add_decl
("/* allocate {mtype} */")
670 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
671 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
672 v
.add
("res->type = (struct type*) &type_{c_name};")
673 v
.add
("res->class = (struct class*) &class_{c_name};")
674 v
.add
("res->value = value;")
675 v
.add
("return (val*)res;")
680 var is_native_array
= mclass
.name
== "NativeArray"
683 if is_native_array
then
684 sig
= "int length, struct type* type"
686 sig
= "struct type* type"
689 #Build instance struct
690 #extern const struct instance_array__NativeArray instance_array__NativeArray;
691 self.header
.add_decl
("struct instance_{c_name} \{")
692 self.header
.add_decl
("const struct type *type;")
693 self.header
.add_decl
("const struct class *class;")
694 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
695 if is_native_array
then
696 # NativeArrays are just a instance header followed by an array of values
697 self.header
.add_decl
("val* values[0];")
699 self.header
.add_decl
("\};")
702 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
703 v
.add_decl
("/* allocate {mtype} */")
704 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
705 var res
= v
.new_named_var
(mtype
, "self")
707 if is_native_array
then
708 var mtype_elt
= mtype
.arguments
.first
709 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
711 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
713 v
.add
("{res}->type = type;")
714 if v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then
715 v
.add
("if(type == NULL) \{")
716 v
.add_abort
("type null")
718 v
.add
("if(type->resolution_table == NULL) \{")
719 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", type->name);")
720 v
.add_abort
("type dead")
723 v
.add
("{res}->class = (struct class*) &class_{c_name};")
725 self.generate_init_attr
(v
, res
, mtype
)
726 v
.add
("return {res};")
729 generate_check_init_instance
(mtype
)
732 redef fun generate_check_init_instance
(mtype
)
734 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
736 var v
= self.new_visitor
737 var c_name
= mtype
.mclass
.c_name
738 var res
= new RuntimeVariable("self", mtype
, mtype
)
739 self.header
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype});")
740 v
.add_decl
("/* allocate {mtype} */")
741 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
742 self.generate_check_attr
(v
, res
, mtype
)
746 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
750 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
751 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
752 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
753 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
755 redef fun display_stats
758 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
765 print
"# size of subtyping tables"
766 print
"\ttotal \tholes"
769 for t
, table
in type_tables
do
770 total
+= table
.length
771 for e
in table
do if e
== null then holes
+= 1
773 print
"\t{total}\t{holes}"
775 print
"# size of resolution tables"
776 print
"\ttotal \tholes"
779 for t
, table
in resolution_tables
do
780 total
+= table
.length
781 for e
in table
do if e
== null then holes
+= 1
783 print
"\t{total}\t{holes}"
785 print
"# size of methods tables"
786 print
"\ttotal \tholes"
789 for t
, table
in method_tables
do
790 total
+= table
.length
791 for e
in table
do if e
== null then holes
+= 1
793 print
"\t{total}\t{holes}"
795 print
"# size of attributes tables"
796 print
"\ttotal \tholes"
799 for t
, table
in attr_tables
do
800 total
+= table
.length
801 for e
in table
do if e
== null then holes
+= 1
803 print
"\t{total}\t{holes}"
807 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
808 class SeparateCompilerVisitor
809 super AbstractCompilerVisitor
811 redef type COMPILER: SeparateCompiler
813 redef fun adapt_signature
(m
, args
)
815 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
816 var recv
= args
.first
817 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
818 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
820 for i
in [0..msignature
.arity
[ do
821 var t
= msignature
.mparameters
[i
].mtype
822 if i
== msignature
.vararg_rank
then
825 args
[i
+1] = self.autobox
(args
[i
+1], t
)
829 redef fun autobox
(value
, mtype
)
831 if value
.mtype
== mtype
then
833 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
835 else if value
.mtype
.ctype
== "val*" then
836 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
837 else if mtype
.ctype
== "val*" then
838 var valtype
= value
.mtype
.as(MClassType)
839 var res
= self.new_var
(mtype
)
840 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
841 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
842 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
845 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
848 # Bad things will appen!
849 var res
= self.new_var
(mtype
)
850 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
851 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
856 # Return a C expression returning the runtime type structure of the value
857 # The point of the method is to works also with primitives types.
858 fun type_info
(value
: RuntimeVariable): String
860 if value
.mtype
.ctype
== "val*" then
861 return "{value}->type"
863 return "(&type_{value.mtype.c_name})"
867 redef fun send
(mmethod
, arguments
)
869 if arguments
.first
.mcasttype
.ctype
!= "val*" then
870 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
873 var res
: nullable RuntimeVariable
874 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
875 var ret
= msignature
.return_mtype
876 if mmethod
.is_new
then
877 ret
= arguments
.first
.mtype
878 res
= self.new_var
(ret
)
879 else if ret
== null then
882 res
= self.new_var
(ret
)
888 var recv
= arguments
.first
891 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
892 for i
in [0..msignature
.arity
[ do
893 var a
= arguments
[i
+1]
894 var t
= msignature
.mparameters
[i
].mtype
895 if i
== msignature
.vararg_rank
then
896 t
= arguments
[i
+1].mcasttype
898 s
.append
(", {t.ctype}")
899 a
= self.autobox
(a
, t
)
903 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
904 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
906 self.add
("if ({recv} == NULL) \{")
907 if mmethod
.name
== "==" then
909 var arg
= arguments
[1]
910 if arg
.mcasttype
isa MNullableType then
911 self.add
("{res} = ({arg} == NULL);")
912 else if arg
.mcasttype
isa MNullType then
913 self.add
("{res} = 1; /* is null */")
915 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
917 else 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} = 0; /* is null */")
925 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
928 self.add_abort
("Reciever is null")
930 self.add
("\} else \{")
932 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
934 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
935 var arg
= arguments
[1]
936 if arg
.mcasttype
isa MNullType then
937 if mmethod
.name
== "==" then
938 self.add
("{res} = 0; /* arg is null but recv is not */")
940 self.add
("{res} = 1; /* arg is null and recv is not */")
950 if ret
== null then r
= "void" else r
= ret
.ctype
951 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
954 self.add
("{res} = {call};")
966 redef fun call
(mmethoddef
, recvtype
, arguments
)
968 var res
: nullable RuntimeVariable
969 var ret
= mmethoddef
.msignature
.return_mtype
970 if mmethoddef
.mproperty
.is_new
then
971 ret
= arguments
.first
.mtype
972 res
= self.new_var
(ret
)
973 else if ret
== null then
976 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
977 res
= self.new_var
(ret
)
980 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
981 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
982 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
983 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
984 frame
.returnlabel
= self.get_name
("RET_LABEL")
985 frame
.returnvar
= res
986 var old_frame
= self.frame
988 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
989 mmethoddef
.compile_inside_to_c
(self, arguments
)
990 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
992 self.frame
= old_frame
997 self.adapt_signature
(mmethoddef
, arguments
)
1000 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1003 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1009 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1011 # FIXME implements a polymorphic access in tables
1012 m
= m
.lookup_next_definition
(m
.mclassdef
.mmodule
, m
.mclassdef
.bound_mtype
)
1013 return self.call
(m
, recvtype
, args
)
1016 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1018 # A vararg must be stored into an new array
1019 # The trick is that the dymaic type of the array may depends on the receiver
1020 # of the method (ie recv) if the static type is unresolved
1021 # This is more complex than usual because the unresolved type must not be resolved
1022 # with the current receiver (ie self).
1023 # Therefore to isolate the resolution from self, a local Frame is created.
1024 # One can see this implementation as an inlined method of the receiver whose only
1025 # job is to allocate the array
1026 var old_frame
= self.frame
1027 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1029 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1030 var res
= self.array_instance
(varargs
, elttype
)
1031 self.frame
= old_frame
1035 redef fun isset_attribute
(a
, recv
)
1037 self.check_recv_notnull
(recv
)
1038 var res
= self.new_var
(bool_type
)
1040 # What is the declared type of the attribute?
1041 var mtype
= a
.intro
.static_mtype
.as(not null)
1042 var intromclassdef
= a
.intro
.mclassdef
1043 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1045 if mtype
isa MNullableType then
1046 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1050 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1051 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1054 if mtype
.ctype
== "val*" then
1055 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1057 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1063 redef fun read_attribute
(a
, recv
)
1065 self.check_recv_notnull
(recv
)
1067 # What is the declared type of the attribute?
1068 var ret
= a
.intro
.static_mtype
.as(not null)
1069 var intromclassdef
= a
.intro
.mclassdef
1070 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1072 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1073 # Get the attribute or a box (ie. always a val*)
1074 var cret
= self.object_type
.as_nullable
1075 var res
= self.new_var
(cret
)
1078 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1080 # Check for Uninitialized attribute
1081 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1082 self.add
("if ({res} == NULL) \{")
1083 self.add_abort
("Uninitialized attribute {a.name}")
1087 # Return the attribute or its unboxed version
1088 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1089 return self.autobox
(res
, ret
)
1091 var res
= self.new_var
(ret
)
1092 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1094 # Check for Uninitialized attribute
1095 if ret
.ctype
== "val*" and 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}")
1105 redef fun write_attribute
(a
, recv
, value
)
1107 self.check_recv_notnull
(recv
)
1109 # What is the declared type of the attribute?
1110 var mtype
= a
.intro
.static_mtype
.as(not null)
1111 var intromclassdef
= a
.intro
.mclassdef
1112 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1114 # Adapt the value to the declared type
1115 value
= self.autobox
(value
, mtype
)
1117 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1118 var attr
= "{recv}->attrs[{a.const_color}]"
1119 if mtype
.ctype
!= "val*" then
1120 assert mtype
isa MClassType
1121 # The attribute is primitive, thus we store it in a box
1122 # The trick is to create the box the first time then resuse the box
1123 self.add
("if ({attr} != NULL) \{")
1124 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1125 self.add
("\} else \{")
1126 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1127 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1130 # The attribute is not primitive, thus store it direclty
1131 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1134 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1138 redef fun init_instance
(mtype
)
1140 var compiler
= self.compiler
1141 if mtype
isa MGenericType and mtype
.need_anchor
then
1142 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1143 var recv
= self.frame
.arguments
.first
1144 var recv_type_info
= self.type_info
(recv
)
1145 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1146 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1148 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1151 compiler
.undead_types
.add
(mtype
)
1152 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
1155 redef fun check_init_instance
(value
, mtype
)
1157 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1158 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1161 redef fun type_test
(value
, mtype
, tag
)
1163 self.add
("/* {value.inspect} isa {mtype} */")
1164 var compiler
= self.compiler
1166 var recv
= self.frame
.arguments
.first
1167 var recv_type_info
= self.type_info
(recv
)
1169 var res
= self.new_var
(bool_type
)
1171 var cltype
= self.get_name
("cltype")
1172 self.add_decl
("int {cltype};")
1173 var idtype
= self.get_name
("idtype")
1174 self.add_decl
("int {idtype};")
1176 var maybe_null
= self.maybe_null
(value
)
1177 var accept_null
= "0"
1179 if ntype
isa MNullableType then
1184 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1185 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1186 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1187 self.compiler
.count_type_test_skipped
[tag
] += 1
1188 self.add
("count_type_test_skipped_{tag}++;")
1193 if ntype
.need_anchor
then
1194 var type_struct
= self.get_name
("type_struct")
1195 self.add_decl
("struct type* {type_struct};")
1197 # Either with resolution_table with a direct resolution
1198 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1199 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1200 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1202 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1204 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1205 self.compiler
.count_type_test_unresolved
[tag
] += 1
1206 self.add
("count_type_test_unresolved_{tag}++;")
1208 self.add
("{cltype} = {type_struct}->color;")
1209 self.add
("{idtype} = {type_struct}->id;")
1210 if maybe_null
and accept_null
== "0" then
1211 var is_nullable
= self.get_name
("is_nullable")
1212 self.add_decl
("short int {is_nullable};")
1213 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1214 accept_null
= is_nullable
.to_s
1216 else if ntype
isa MClassType then
1217 compiler
.undead_types
.add
(mtype
)
1218 self.add
("{cltype} = type_{mtype.c_name}.color;")
1219 self.add
("{idtype} = type_{mtype.c_name}.id;")
1220 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1221 self.compiler
.count_type_test_resolved
[tag
] += 1
1222 self.add
("count_type_test_resolved_{tag}++;")
1225 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1228 # check color is in table
1230 self.add
("if({value} == NULL) \{")
1231 self.add
("{res} = {accept_null};")
1232 self.add
("\} else \{")
1234 var value_type_info
= self.type_info
(value
)
1235 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1236 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1238 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1239 self.add
("{res} = 0;")
1240 self.add
("\} else \{")
1241 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1250 redef fun is_same_type_test
(value1
, value2
)
1252 var res
= self.new_var
(bool_type
)
1253 # Swap values to be symetric
1254 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1259 if value1
.mtype
.ctype
!= "val*" then
1260 if value2
.mtype
== value1
.mtype
then
1261 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1262 else if value2
.mtype
.ctype
!= "val*" then
1263 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1265 var mtype1
= value1
.mtype
.as(MClassType)
1266 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1269 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1274 redef fun class_name_string
(value
)
1276 var res
= self.get_name
("var_class_name")
1277 self.add_decl
("const char* {res};")
1278 if value
.mtype
.ctype
== "val*" then
1279 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1281 self.add
"{res} = type_{value.mtype.c_name}.name;"
1286 redef fun equal_test
(value1
, value2
)
1288 var res
= self.new_var
(bool_type
)
1289 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1294 if value1
.mtype
.ctype
!= "val*" then
1295 if value2
.mtype
== value1
.mtype
then
1296 self.add
("{res} = {value1} == {value2};")
1297 else if value2
.mtype
.ctype
!= "val*" then
1298 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1300 var mtype1
= value1
.mtype
.as(MClassType)
1301 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1302 self.add
("if ({res}) \{")
1303 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1308 var maybe_null
= true
1309 var test
= new Array[String]
1310 var t1
= value1
.mcasttype
1311 if t1
isa MNullableType then
1312 test
.add
("{value1} != NULL")
1317 var t2
= value2
.mcasttype
1318 if t2
isa MNullableType then
1319 test
.add
("{value2} != NULL")
1325 var incompatible
= false
1327 if t1
.ctype
!= "val*" then
1330 # No need to compare class
1331 else if t2
.ctype
!= "val*" then
1333 else if can_be_primitive
(value2
) then
1334 test
.add
("{value1}->class == {value2}->class")
1338 else if t2
.ctype
!= "val*" then
1340 if can_be_primitive
(value1
) then
1341 test
.add
("{value1}->class == {value2}->class")
1349 if incompatible
then
1351 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1354 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1358 if primitive
!= null then
1359 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1360 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1361 test
.add
("{value1}->class == {value2}->class")
1362 var s
= new Array[String]
1363 for t
, v
in self.compiler
.box_kinds
do
1364 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1366 test
.add
("({s.join(" || ")})")
1368 self.add
("{res} = {value1} == {value2};")
1371 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1375 fun can_be_primitive
(value
: RuntimeVariable): Bool
1377 var t
= value
.mcasttype
1378 if t
isa MNullableType then t
= t
.mtype
1379 if not t
isa MClassType then return false
1380 var k
= t
.mclass
.kind
1381 return k
== interface_kind
or t
.ctype
!= "val*"
1384 fun maybe_null
(value
: RuntimeVariable): Bool
1386 var t
= value
.mcasttype
1387 return t
isa MNullableType or t
isa MNullType
1390 redef fun array_instance
(array
, elttype
)
1392 var nclass
= self.get_class
("NativeArray")
1393 var arrayclass
= self.get_class
("Array")
1394 var arraytype
= arrayclass
.get_mtype
([elttype
])
1395 var res
= self.init_instance
(arraytype
)
1396 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1397 var length
= self.int_instance
(array
.length
)
1398 var nat
= native_array_instance
(elttype
, length
)
1399 for i
in [0..array
.length
[ do
1400 var r
= self.autobox
(array
[i
], self.object_type
)
1401 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1403 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1404 self.check_init_instance
(res
, arraytype
)
1409 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1411 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1412 assert mtype
isa MGenericType
1413 var compiler
= self.compiler
1414 if mtype
.need_anchor
then
1415 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1416 var recv
= self.frame
.arguments
.first
1417 var recv_type_info
= self.type_info
(recv
)
1418 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1419 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1421 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1424 compiler
.undead_types
.add
(mtype
)
1425 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype
)
1428 redef fun native_array_def
(pname
, ret_type
, arguments
)
1430 var elttype
= arguments
.first
.mtype
1431 var nclass
= self.get_class
("NativeArray")
1432 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1433 if pname
== "[]" then
1434 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1436 else if pname
== "[]=" then
1437 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1439 else if pname
== "copy_to" then
1440 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1441 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1446 redef fun calloc_array
(ret_type
, arguments
)
1448 var mclass
= self.get_class
("ArrayCapable")
1449 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1450 var res
= self.native_array_instance
(ft
, arguments
[1])
1454 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1455 assert mtype
.need_anchor
1456 var compiler
= self.compiler
1457 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1458 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1460 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1464 # The C function associated to a methoddef separately compiled
1465 class SeparateRuntimeFunction
1466 super AbstractRuntimeFunction
1468 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1470 redef fun to_s
do return self.mmethoddef
.to_s
1472 redef fun compile_to_c
(compiler
)
1474 var mmethoddef
= self.mmethoddef
1476 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1477 var v
= compiler
.new_visitor
1478 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1479 var arguments
= new Array[RuntimeVariable]
1480 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1483 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1485 var sig
= new Buffer
1486 var comment
= new Buffer
1487 var ret
= msignature
.return_mtype
1489 sig
.append
("{ret.ctype} ")
1490 else if mmethoddef
.mproperty
.is_new
then
1492 sig
.append
("{ret.ctype} ")
1496 sig
.append
(self.c_name
)
1497 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1498 comment
.append
("(self: {selfvar}")
1499 arguments
.add
(selfvar
)
1500 for i
in [0..msignature
.arity
[ do
1501 var mtype
= msignature
.mparameters
[i
].mtype
1502 if i
== msignature
.vararg_rank
then
1503 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1505 comment
.append
(", {mtype}")
1506 sig
.append
(", {mtype.ctype} p{i}")
1507 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1508 arguments
.add
(argvar
)
1513 comment
.append
(": {ret}")
1515 compiler
.header
.add_decl
("{sig};")
1517 v
.add_decl
("/* method {self} for {comment} */")
1518 v
.add_decl
("{sig} \{")
1520 frame
.returnvar
= v
.new_var
(ret
)
1522 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1524 if recv
!= arguments
.first
.mtype
then
1525 #print "{self} {recv} {arguments.first}"
1527 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1529 v
.add
("{frame.returnlabel.as(not null)}:;")
1531 v
.add
("return {frame.returnvar.as(not null)};")
1537 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1538 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1539 class VirtualRuntimeFunction
1540 super AbstractRuntimeFunction
1542 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1544 redef fun to_s
do return self.mmethoddef
.to_s
1546 redef fun compile_to_c
(compiler
)
1548 var mmethoddef
= self.mmethoddef
1550 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1551 var v
= compiler
.new_visitor
1552 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1553 var arguments
= new Array[RuntimeVariable]
1554 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1557 var sig
= new Buffer
1558 var comment
= new Buffer
1560 # Because the function is virtual, the signature must match the one of the original class
1561 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1562 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1563 var ret
= msignature
.return_mtype
1565 sig
.append
("{ret.ctype} ")
1566 else if mmethoddef
.mproperty
.is_new
then
1568 sig
.append
("{ret.ctype} ")
1572 sig
.append
(self.c_name
)
1573 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1574 comment
.append
("(self: {selfvar}")
1575 arguments
.add
(selfvar
)
1576 for i
in [0..msignature
.arity
[ do
1577 var mtype
= msignature
.mparameters
[i
].mtype
1578 if i
== msignature
.vararg_rank
then
1579 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1581 comment
.append
(", {mtype}")
1582 sig
.append
(", {mtype.ctype} p{i}")
1583 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1584 arguments
.add
(argvar
)
1589 comment
.append
(": {ret}")
1591 compiler
.header
.add_decl
("{sig};")
1593 v
.add_decl
("/* method {self} for {comment} */")
1594 v
.add_decl
("{sig} \{")
1596 frame
.returnvar
= v
.new_var
(ret
)
1598 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1600 if recv
!= arguments
.first
.mtype
then
1601 #print "{self} {recv} {arguments.first}"
1603 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1605 v
.add
("{frame.returnlabel.as(not null)}:;")
1607 v
.add
("return {frame.returnvar.as(not null)};")
1613 redef fun call
(v
, arguments
) do abort
1617 fun const_color
: String do return "COLOR_{c_name}"
1620 redef class MProperty
1621 fun const_color
: String do return "COLOR_{c_name}"