nitg: move `import compiler_ffi` to nitg
[nit.git] / src / separate_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # Separate compilation of a Nit program
16 module separate_compiler
17
18 import abstract_compiler
19 import layout_builders
20 import rapid_type_analysis
21
22 # Add separate compiler specific options
23 redef class ToolContext
24 # --separate
25 var opt_separate: OptionBool = new OptionBool("Use separate compilation", "--separate")
26 # --no-inline-intern
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 # --tables-metrics
41 var opt_tables_metrics: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
42
43 redef init
44 do
45 super
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)
55 end
56 end
57
58 redef class ModelBuilder
59 fun run_separate_compiler(mainmodule: MModule, runtime_type_analysis: nullable RapidTypeAnalysis)
60 do
61 var time0 = get_time
62 self.toolcontext.info("*** GENERATING C ***", 1)
63
64 var compiler = new SeparateCompiler(mainmodule, self, runtime_type_analysis)
65 compiler.compile_header
66
67 # compile class structures
68 self.toolcontext.info("Property coloring", 2)
69 compiler.new_file("{mainmodule.name}.classes")
70 compiler.do_property_coloring
71 for m in mainmodule.in_importation.greaters do
72 for mclass in m.intro_mclasses do
73 if mclass.kind == abstract_kind or mclass.kind == interface_kind then continue
74 compiler.compile_class_to_c(mclass)
75 end
76 end
77
78 # The main function of the C
79 compiler.new_file("{mainmodule.name}.main")
80 compiler.compile_main_function
81
82 # compile methods
83 for m in mainmodule.in_importation.greaters do
84 self.toolcontext.info("Generate C for module {m}", 2)
85 compiler.new_file("{m.name}.sep")
86 compiler.compile_module_to_c(m)
87 end
88
89 # compile live & cast type structures
90 self.toolcontext.info("Type coloring", 2)
91 compiler.new_file("{mainmodule.name}.types")
92 var mtypes = compiler.do_type_coloring
93 for t in mtypes do
94 compiler.compile_type_to_c(t)
95 end
96 # compile remaining types structures (useless but needed for the symbol resolution at link-time)
97 for t in compiler.undead_types do
98 if mtypes.has(t) then continue
99 compiler.compile_type_to_c(t)
100 end
101
102 compiler.display_stats
103
104 var time1 = get_time
105 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
106 write_and_make(compiler)
107 end
108 end
109
110 # Singleton that store the knowledge about the separate compilation process
111 class SeparateCompiler
112 super AbstractCompiler
113
114 redef type VISITOR: SeparateCompilerVisitor
115
116 # The result of the RTA (used to know live types and methods)
117 var runtime_type_analysis: nullable RapidTypeAnalysis
118
119 private var undead_types: Set[MType] = new HashSet[MType]
120 private var live_unresolved_types: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
121
122 private var type_layout: nullable Layout[MType]
123 private var resolution_layout: nullable Layout[MType]
124 protected var method_layout: nullable Layout[PropertyLayoutElement]
125 protected var attr_layout: nullable Layout[MAttribute]
126
127 init(mainmodule: MModule, mmbuilder: ModelBuilder, runtime_type_analysis: nullable RapidTypeAnalysis) do
128 super(mainmodule, mmbuilder)
129 var file = new_file("nit.common")
130 self.header = new CodeWriter(file)
131 self.runtime_type_analysis = runtime_type_analysis
132 self.compile_box_kinds
133 end
134
135 redef fun compile_header_structs do
136 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
137 self.compile_header_attribute_structs
138 self.header.add_decl("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
139
140 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
141 self.header.add_decl("struct type \{ int id; const char *name; int color; short int is_nullable; const struct types *resolution_table; int table_size; int type_table[]; \}; /* general C type representing a Nit type. */")
142 self.header.add_decl("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
143
144 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
145 self.header.add_decl("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
146 else
147 self.header.add_decl("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
148 end
149
150 if modelbuilder.toolcontext.opt_phmod_typing.value then
151 self.header.add_decl("#define HASH(mask, id) ((mask)%(id))")
152 else if modelbuilder.toolcontext.opt_phand_typing.value then
153 self.header.add_decl("#define HASH(mask, id) ((mask)&(id))")
154 end
155
156 self.header.add_decl("typedef struct instance val; /* general C type representing a Nit instance. */")
157 end
158
159 fun compile_header_attribute_structs
160 do
161 if modelbuilder.toolcontext.opt_no_union_attribute.value then
162 self.header.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
163 else
164 self.header.add_decl("typedef union \{")
165 self.header.add_decl("void* val;")
166 for c, v in self.box_kinds do
167 var t = c.mclass_type
168 self.header.add_decl("{t.ctype} {t.ctypename};")
169 end
170 self.header.add_decl("\} nitattribute_t; /* general C type representing a Nit attribute. */")
171 end
172 end
173
174 fun compile_box_kinds
175 do
176 # Collect all bas box class
177 # FIXME: this is not completely fine with a separate compilation scheme
178 for classname in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
179 var classes = self.mainmodule.model.get_mclasses_by_name(classname)
180 if classes == null then continue
181 assert classes.length == 1 else print classes.join(", ")
182 self.box_kinds[classes.first] = self.box_kinds.length + 1
183 end
184 end
185
186 var box_kinds = new HashMap[MClass, Int]
187
188 fun box_kind_of(mclass: MClass): Int
189 do
190 if mclass.mclass_type.ctype == "val*" then
191 return 0
192 else if mclass.kind == extern_kind then
193 return self.box_kinds[self.mainmodule.get_primitive_class("Pointer")]
194 else
195 return self.box_kinds[mclass]
196 end
197
198 end
199
200 fun compile_color_consts(colors: Map[Object, Int]) do
201 var v = new_visitor
202 for m, c in colors do
203 compile_color_const(v, m, c)
204 end
205 end
206
207 fun compile_color_const(v: SeparateCompilerVisitor, m: Object, color: Int) do
208 if color_consts_done.has(m) then return
209 if m isa MProperty then
210 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
211 self.provide_declaration(m.const_color, "#define {m.const_color} {color}")
212 else
213 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
214 v.add("const int {m.const_color} = {color};")
215 end
216 else if m isa MPropDef then
217 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
218 self.provide_declaration(m.const_color, "#define {m.const_color} {color}")
219 else
220 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
221 v.add("const int {m.const_color} = {color};")
222 end
223 else if m isa MType then
224 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
225 self.provide_declaration(m.const_color, "#define {m.const_color} {color}")
226 else
227 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
228 v.add("const int {m.const_color} = {color};")
229 end
230 end
231 color_consts_done.add(m)
232 end
233
234 private var color_consts_done = new HashSet[Object]
235
236 # colorize classe properties
237 fun do_property_coloring do
238 var mclasses = new HashSet[MClass].from(modelbuilder.model.mclasses)
239
240 # Layouts
241 var method_layout_builder: PropertyLayoutBuilder[PropertyLayoutElement]
242 var attribute_layout_builder: PropertyLayoutBuilder[MAttribute]
243 #FIXME PH and BM layouts too slow for large programs
244 #if modelbuilder.toolcontext.opt_bm_typing.value then
245 # method_layout_builder = new MMethodBMizer(self.mainmodule)
246 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
247 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
248 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
249 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
250 #else if modelbuilder.toolcontext.opt_phand_typing.value then
251 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
252 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
253 #else
254
255 var class_layout_builder = new MClassColorer(self.mainmodule)
256 class_layout_builder.build_layout(mclasses)
257 method_layout_builder = new MPropertyColorer[PropertyLayoutElement](self.mainmodule, class_layout_builder)
258 attribute_layout_builder = new MPropertyColorer[MAttribute](self.mainmodule, class_layout_builder)
259 #end
260
261 # lookup properties to build layout with
262 var mmethods = new HashMap[MClass, Set[PropertyLayoutElement]]
263 var mattributes = new HashMap[MClass, Set[MAttribute]]
264 for mclass in mclasses do
265 mmethods[mclass] = new HashSet[PropertyLayoutElement]
266 mattributes[mclass] = new HashSet[MAttribute]
267 for mprop in self.mainmodule.properties(mclass) do
268 if mprop isa MMethod then
269 mmethods[mclass].add(mprop)
270 else if mprop isa MAttribute then
271 mattributes[mclass].add(mprop)
272 end
273 end
274 end
275
276 # Collect all super calls (dead or not)
277 var all_super_calls = new HashSet[MMethodDef]
278 for mmodule in self.mainmodule.in_importation.greaters do
279 for mclassdef in mmodule.mclassdefs do
280 for mpropdef in mclassdef.mpropdefs do
281 if not mpropdef isa MMethodDef then continue
282 if mpropdef.has_supercall then
283 all_super_calls.add(mpropdef)
284 end
285 end
286 end
287 end
288
289 # lookup super calls and add it to the list of mmethods to build layout with
290 var super_calls
291 if runtime_type_analysis != null then
292 super_calls = runtime_type_analysis.live_super_sends
293 else
294 super_calls = all_super_calls
295 end
296
297 for mmethoddef in super_calls do
298 var mclass = mmethoddef.mclassdef.mclass
299 mmethods[mclass].add(mmethoddef)
300 for descendant in mclass.in_hierarchy(self.mainmodule).smallers do
301 mmethods[descendant].add(mmethoddef)
302 end
303 end
304
305 # methods coloration
306 self.method_layout = method_layout_builder.build_layout(mmethods)
307 self.method_tables = build_method_tables(mclasses, super_calls)
308 self.compile_color_consts(method_layout.pos)
309
310 # attribute null color to dead supercalls
311 for mpropdef in all_super_calls do
312 if super_calls.has(mpropdef) then continue
313 compile_color_const(new_visitor, mpropdef, -1)
314 end
315
316 # attributes coloration
317 self.attr_layout = attribute_layout_builder.build_layout(mattributes)
318 self.attr_tables = build_attr_tables(mclasses)
319 self.compile_color_consts(attr_layout.pos)
320 end
321
322 fun build_method_tables(mclasses: Set[MClass], super_calls: Set[MMethodDef]): Map[MClass, Array[nullable MPropDef]] do
323 var layout = self.method_layout
324 var tables = new HashMap[MClass, Array[nullable MPropDef]]
325 for mclass in mclasses do
326 var table = new Array[nullable MPropDef]
327 var supercalls = new List[MMethodDef]
328
329 # first, fill table from parents by reverse linearization order
330 var parents = new Array[MClass]
331 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
332 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
333 self.mainmodule.linearize_mclasses(parents)
334 end
335
336 for parent in parents do
337 if parent == mclass then continue
338 for mproperty in self.mainmodule.properties(parent) do
339 if not mproperty isa MMethod then continue
340 var color = layout.pos[mproperty]
341 if table.length <= color then
342 for i in [table.length .. color[ do
343 table[i] = null
344 end
345 end
346 for mpropdef in mproperty.mpropdefs do
347 if mpropdef.mclassdef.mclass == parent then
348 table[color] = mpropdef
349 end
350 end
351 end
352
353 # lookup for super calls in super classes
354 for mmethoddef in super_calls do
355 for mclassdef in parent.mclassdefs do
356 if mclassdef.mpropdefs.has(mmethoddef) then
357 supercalls.add(mmethoddef)
358 end
359 end
360 end
361 end
362
363 # then override with local properties
364 for mproperty in self.mainmodule.properties(mclass) do
365 if not mproperty isa MMethod then continue
366 var color = layout.pos[mproperty]
367 if table.length <= color then
368 for i in [table.length .. color[ do
369 table[i] = null
370 end
371 end
372 for mpropdef in mproperty.mpropdefs do
373 if mpropdef.mclassdef.mclass == mclass then
374 table[color] = mpropdef
375 end
376 end
377 end
378
379 # lookup for super calls in local class
380 for mmethoddef in super_calls do
381 for mclassdef in mclass.mclassdefs do
382 if mclassdef.mpropdefs.has(mmethoddef) then
383 supercalls.add(mmethoddef)
384 end
385 end
386 end
387 # insert super calls in table according to receiver
388 for supercall in supercalls do
389 var color = layout.pos[supercall]
390 if table.length <= color then
391 for i in [table.length .. color[ do
392 table[i] = null
393 end
394 end
395 var mmethoddef = supercall.lookup_next_definition(self.mainmodule, mclass.intro.bound_mtype)
396 table[color] = mmethoddef
397 end
398 tables[mclass] = table
399 end
400 return tables
401 end
402
403 fun build_attr_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
404 var layout = self.attr_layout
405 var tables = new HashMap[MClass, Array[nullable MPropDef]]
406 for mclass in mclasses do
407 var table = new Array[nullable MPropDef]
408 # first, fill table from parents by reverse linearization order
409 var parents = new Array[MClass]
410 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
411 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
412 self.mainmodule.linearize_mclasses(parents)
413 end
414 for parent in parents do
415 if parent == mclass then continue
416 for mproperty in self.mainmodule.properties(parent) do
417 if not mproperty isa MAttribute then continue
418 var color = layout.pos[mproperty]
419 if table.length <= color then
420 for i in [table.length .. color[ do
421 table[i] = null
422 end
423 end
424 for mpropdef in mproperty.mpropdefs do
425 if mpropdef.mclassdef.mclass == parent then
426 table[color] = mpropdef
427 end
428 end
429 end
430 end
431
432 # then override with local properties
433 for mproperty in self.mainmodule.properties(mclass) do
434 if not mproperty isa MAttribute then continue
435 var color = layout.pos[mproperty]
436 if table.length <= color then
437 for i in [table.length .. color[ do
438 table[i] = null
439 end
440 end
441 for mpropdef in mproperty.mpropdefs do
442 if mpropdef.mclassdef.mclass == mclass then
443 table[color] = mpropdef
444 end
445 end
446 end
447 tables[mclass] = table
448 end
449 return tables
450 end
451
452 # colorize live types of the program
453 private fun do_type_coloring: POSet[MType] do
454 var mtypes = new HashSet[MType]
455 mtypes.add_all(self.runtime_type_analysis.live_types)
456 mtypes.add_all(self.runtime_type_analysis.live_cast_types)
457 for c in self.box_kinds.keys do
458 mtypes.add(c.mclass_type)
459 end
460
461 # Typing Layout
462 var layout_builder: TypingLayoutBuilder[MType]
463 if modelbuilder.toolcontext.opt_bm_typing.value then
464 layout_builder = new MTypeBMizer(self.mainmodule)
465 else if modelbuilder.toolcontext.opt_phmod_typing.value then
466 layout_builder = new MTypeHasher(new PHModOperator, self.mainmodule)
467 else if modelbuilder.toolcontext.opt_phand_typing.value then
468 layout_builder = new MTypeHasher(new PHAndOperator, self.mainmodule)
469 else
470 layout_builder = new MTypeColorer(self.mainmodule)
471 end
472
473 # colorize types
474 self.type_layout = layout_builder.build_layout(mtypes)
475 var poset = layout_builder.poset.as(not null)
476 self.type_tables = self.build_type_tables(poset)
477
478 # VT and FT are stored with other unresolved types in the big resolution_tables
479 self.compile_resolution_tables(mtypes)
480
481 return poset
482 end
483
484 # Build type tables
485 fun build_type_tables(mtypes: POSet[MType]): Map[MType, Array[nullable MType]] do
486 var tables = new HashMap[MType, Array[nullable MType]]
487 var layout = self.type_layout
488 for mtype in mtypes do
489 var table = new Array[nullable MType]
490 for sup in mtypes[mtype].greaters do
491 var color: Int
492 if layout isa PHLayout[MType, MType] then
493 color = layout.hashes[mtype][sup]
494 else
495 color = layout.pos[sup]
496 end
497 if table.length <= color then
498 for i in [table.length .. color[ do
499 table[i] = null
500 end
501 end
502 table[color] = sup
503 end
504 tables[mtype] = table
505 end
506 return tables
507 end
508
509 protected fun compile_resolution_tables(mtypes: Set[MType]) do
510 # resolution_tables is used to perform a type resolution at runtime in O(1)
511
512 # During the visit of the body of classes, live_unresolved_types are collected
513 # and associated to
514 # Collect all live_unresolved_types (visited in the body of classes)
515
516 # Determinate fo each livetype what are its possible requested anchored types
517 var mtype2unresolved = new HashMap[MClassType, Set[MType]]
518 for mtype in self.runtime_type_analysis.live_types do
519 var set = new HashSet[MType]
520 for cd in mtype.collect_mclassdefs(self.mainmodule) do
521 if self.live_unresolved_types.has_key(cd) then
522 set.add_all(self.live_unresolved_types[cd])
523 end
524 end
525 mtype2unresolved[mtype] = set
526 end
527
528 # Compute the table layout with the prefered method
529 var resolution_builder: ResolutionLayoutBuilder
530 if modelbuilder.toolcontext.opt_bm_typing.value then
531 resolution_builder = new ResolutionBMizer
532 else if modelbuilder.toolcontext.opt_phmod_typing.value then
533 resolution_builder = new ResolutionHasher(new PHModOperator)
534 else if modelbuilder.toolcontext.opt_phand_typing.value then
535 resolution_builder = new ResolutionHasher(new PHAndOperator)
536 else
537 resolution_builder = new ResolutionColorer
538 end
539 self.resolution_layout = resolution_builder.build_layout(mtype2unresolved)
540 self.resolution_tables = self.build_resolution_tables(mtype2unresolved)
541
542 # Compile a C constant for each collected unresolved type.
543 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
544 var all_unresolved = new HashSet[MType]
545 for t in self.live_unresolved_types.values do
546 all_unresolved.add_all(t)
547 end
548 var all_unresolved_types_colors = new HashMap[MType, Int]
549 for t in all_unresolved do
550 if self.resolution_layout.pos.has_key(t) then
551 all_unresolved_types_colors[t] = self.resolution_layout.pos[t]
552 else
553 all_unresolved_types_colors[t] = -1
554 end
555 end
556 self.compile_color_consts(all_unresolved_types_colors)
557
558 #print "tables"
559 #for k, v in unresolved_types_tables.as(not null) do
560 # print "{k}: {v.join(", ")}"
561 #end
562 #print ""
563 end
564
565 fun build_resolution_tables(elements: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
566 var tables = new HashMap[MClassType, Array[nullable MType]]
567 var layout = self.resolution_layout
568 for mclasstype, mtypes in elements do
569 var table = new Array[nullable MType]
570 for mtype in mtypes do
571 var color: Int
572 if layout isa PHLayout[MClassType, MType] then
573 color = layout.hashes[mclasstype][mtype]
574 else
575 color = layout.pos[mtype]
576 end
577 if table.length <= color then
578 for i in [table.length .. color[ do
579 table[i] = null
580 end
581 end
582 table[color] = mtype
583 end
584 tables[mclasstype] = table
585 end
586 return tables
587 end
588
589 # Separately compile all the method definitions of the module
590 fun compile_module_to_c(mmodule: MModule)
591 do
592 var old_module = self.mainmodule
593 self.mainmodule = mmodule
594 for cd in mmodule.mclassdefs do
595 for pd in cd.mpropdefs do
596 if not pd isa MMethodDef then continue
597 #print "compile {pd} @ {cd} @ {mmodule}"
598 var r = pd.separate_runtime_function
599 r.compile_to_c(self)
600 var r2 = pd.virtual_runtime_function
601 r2.compile_to_c(self)
602 end
603 end
604 self.mainmodule = old_module
605 end
606
607 # Globaly compile the type structure of a live type
608 fun compile_type_to_c(mtype: MType)
609 do
610 assert not mtype.need_anchor
611 var layout = self.type_layout
612 var is_live = mtype isa MClassType and runtime_type_analysis.live_types.has(mtype)
613 var is_cast_live = runtime_type_analysis.live_cast_types.has(mtype)
614 var c_name = mtype.c_name
615 var v = new SeparateCompilerVisitor(self)
616 v.add_decl("/* runtime type {mtype} */")
617
618 # extern const struct type_X
619 self.provide_declaration("type_{c_name}", "extern const struct type type_{c_name};")
620
621 # const struct type_X
622 v.add_decl("const struct type type_{c_name} = \{")
623
624 # type id (for cast target)
625 if is_cast_live then
626 v.add_decl("{layout.ids[mtype]},")
627 else
628 v.add_decl("-1, /*CAST DEAD*/")
629 end
630
631 # type name
632 v.add_decl("\"{mtype}\", /* class_name_string */")
633
634 # type color (for cast target)
635 if is_cast_live then
636 if layout isa PHLayout[MType, MType] then
637 v.add_decl("{layout.masks[mtype]},")
638 else
639 v.add_decl("{layout.pos[mtype]},")
640 end
641 else
642 v.add_decl("-1, /*CAST DEAD*/")
643 end
644
645 # is_nullable bit
646 if mtype isa MNullableType then
647 v.add_decl("1,")
648 else
649 v.add_decl("0,")
650 end
651
652 # resolution table (for receiver)
653 if is_live then
654 var mclass_type = mtype
655 if mclass_type isa MNullableType then mclass_type = mclass_type.mtype
656 assert mclass_type isa MClassType
657 if resolution_tables[mclass_type].is_empty then
658 v.add_decl("NULL, /*NO RESOLUTIONS*/")
659 else
660 compile_type_resolution_table(mtype)
661 v.require_declaration("resolution_table_{c_name}")
662 v.add_decl("&resolution_table_{c_name},")
663 end
664 else
665 v.add_decl("NULL, /*DEAD*/")
666 end
667
668 # cast table (for receiver)
669 if is_live then
670 v.add_decl("{self.type_tables[mtype].length},")
671 v.add_decl("\{")
672 for stype in self.type_tables[mtype] do
673 if stype == null then
674 v.add_decl("-1, /* empty */")
675 else
676 v.add_decl("{layout.ids[stype]}, /* {stype} */")
677 end
678 end
679 v.add_decl("\},")
680 else
681 v.add_decl("0, \{\}, /*DEAD TYPE*/")
682 end
683 v.add_decl("\};")
684 end
685
686 fun compile_type_resolution_table(mtype: MType) do
687
688 var mclass_type: MClassType
689 if mtype isa MNullableType then
690 mclass_type = mtype.mtype.as(MClassType)
691 else
692 mclass_type = mtype.as(MClassType)
693 end
694
695 var layout = self.resolution_layout
696
697 # extern const struct resolution_table_X resolution_table_X
698 self.provide_declaration("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
699
700 # const struct fts_table_X fts_table_X
701 var v = new_visitor
702 v.add_decl("const struct types resolution_table_{mtype.c_name} = \{")
703 if layout isa PHLayout[MClassType, MType] then
704 v.add_decl("{layout.masks[mclass_type]},")
705 else
706 v.add_decl("0, /* dummy */")
707 end
708 v.add_decl("\{")
709 for t in self.resolution_tables[mclass_type] do
710 if t == null then
711 v.add_decl("NULL, /* empty */")
712 else
713 # The table stores the result of the type resolution
714 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
715 # the value stored is tv.
716 var tv = t.resolve_for(mclass_type, mclass_type, self.mainmodule, true)
717 # FIXME: What typeids means here? How can a tv not be live?
718 if self.type_layout.ids.has_key(tv) then
719 v.require_declaration("type_{tv.c_name}")
720 v.add_decl("&type_{tv.c_name}, /* {t}: {tv} */")
721 else
722 v.add_decl("NULL, /* empty ({t}: {tv} not a live type) */")
723 end
724 end
725 end
726 v.add_decl("\}")
727 v.add_decl("\};")
728 end
729
730 # Globally compile the table of the class mclass
731 # In a link-time optimisation compiler, tables are globally computed
732 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
733 fun compile_class_to_c(mclass: MClass)
734 do
735 var mtype = mclass.intro.bound_mtype
736 var c_name = mclass.c_name
737 var c_instance_name = mclass.c_instance_name
738
739 var vft = self.method_tables[mclass]
740 var attrs = self.attr_tables[mclass]
741 var v = new_visitor
742
743 var is_dead = runtime_type_analysis != null and not runtime_type_analysis.live_classes.has(mclass) and mtype.ctype == "val*" and mclass.name != "NativeArray"
744
745 v.add_decl("/* runtime class {c_name} */")
746
747 # Build class vft
748 if not is_dead then
749 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
750 v.add_decl("const struct class class_{c_name} = \{")
751 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
752 v.add_decl("\{")
753 for i in [0 .. vft.length[ do
754 var mpropdef = vft[i]
755 if mpropdef == null then
756 v.add_decl("NULL, /* empty */")
757 else
758 assert mpropdef isa MMethodDef
759 var rf = mpropdef.virtual_runtime_function
760 v.require_declaration(rf.c_name)
761 v.add_decl("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
762 end
763 end
764 v.add_decl("\}")
765 v.add_decl("\};")
766 end
767
768 if mtype.ctype != "val*" then
769 if mtype.mclass.name == "Pointer" or mtype.mclass.kind != extern_kind then
770 #Build instance struct
771 self.header.add_decl("struct instance_{c_instance_name} \{")
772 self.header.add_decl("const struct type *type;")
773 self.header.add_decl("const struct class *class;")
774 self.header.add_decl("{mtype.ctype} value;")
775 self.header.add_decl("\};")
776 end
777
778 if not self.runtime_type_analysis.live_types.has(mtype) then return
779
780 #Build BOX
781 self.provide_declaration("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype});")
782 v.add_decl("/* allocate {mtype} */")
783 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
784 v.add("struct instance_{c_instance_name}*res = nit_alloc(sizeof(struct instance_{c_instance_name}));")
785 v.require_declaration("type_{c_name}")
786 v.add("res->type = &type_{c_name};")
787 v.require_declaration("class_{c_name}")
788 v.add("res->class = &class_{c_name};")
789 v.add("res->value = value;")
790 v.add("return (val*)res;")
791 v.add("\}")
792 return
793 else if mclass.name == "NativeArray" then
794 #Build instance struct
795 self.header.add_decl("struct instance_{c_instance_name} \{")
796 self.header.add_decl("const struct type *type;")
797 self.header.add_decl("const struct class *class;")
798 # NativeArrays are just a instance header followed by an array of values
799 self.header.add_decl("val* values[0];")
800 self.header.add_decl("\};")
801
802 #Build NEW
803 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
804 v.add_decl("/* allocate {mtype} */")
805 v.add_decl("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
806 var res = v.new_named_var(mtype, "self")
807 res.is_exact = true
808 var mtype_elt = mtype.arguments.first
809 v.add("{res} = nit_alloc(sizeof(struct instance_{c_instance_name}) + length*sizeof({mtype_elt.ctype}));")
810 v.add("{res}->type = type;")
811 hardening_live_type(v, "type")
812 v.require_declaration("class_{c_name}")
813 v.add("{res}->class = &class_{c_name};")
814 v.add("return {res};")
815 v.add("\}")
816 return
817 end
818
819 #Build NEW
820 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
821 v.add_decl("/* allocate {mtype} */")
822 v.add_decl("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
823 if is_dead then
824 v.add_abort("{mclass} is DEAD")
825 else
826 var res = v.new_named_var(mtype, "self")
827 res.is_exact = true
828 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
829 v.add("{res}->type = type;")
830 hardening_live_type(v, "type")
831 v.require_declaration("class_{c_name}")
832 v.add("{res}->class = &class_{c_name};")
833 self.generate_init_attr(v, res, mtype)
834 v.add("return {res};")
835 end
836 v.add("\}")
837 end
838
839 # Add a dynamic test to ensure that the type referenced by `t` is a live type
840 fun hardening_live_type(v: VISITOR, t: String)
841 do
842 if not v.compiler.modelbuilder.toolcontext.opt_hardening.value then return
843 v.add("if({t} == NULL) \{")
844 v.add_abort("type null")
845 v.add("\}")
846 v.add("if({t}->table_size == 0) \{")
847 v.add("fprintf(stderr, \"Insantiation of a dead type: %s\\n\", {t}->name);")
848 v.add_abort("type dead")
849 v.add("\}")
850 end
851
852 redef fun new_visitor do return new SeparateCompilerVisitor(self)
853
854 # Stats
855
856 private var type_tables: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
857 private var resolution_tables: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
858 protected var method_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
859 protected var attr_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
860
861 redef fun display_stats
862 do
863 super
864 if self.modelbuilder.toolcontext.opt_tables_metrics.value then
865 display_sizes
866 end
867 end
868
869 fun display_sizes
870 do
871 print "# size of subtyping tables"
872 print "\ttotal \tholes"
873 var total = 0
874 var holes = 0
875 for t, table in type_tables do
876 total += table.length
877 for e in table do if e == null then holes += 1
878 end
879 print "\t{total}\t{holes}"
880
881 print "# size of resolution tables"
882 print "\ttotal \tholes"
883 total = 0
884 holes = 0
885 for t, table in resolution_tables do
886 total += table.length
887 for e in table do if e == null then holes += 1
888 end
889 print "\t{total}\t{holes}"
890
891 print "# size of methods tables"
892 print "\ttotal \tholes"
893 total = 0
894 holes = 0
895 for t, table in method_tables do
896 total += table.length
897 for e in table do if e == null then holes += 1
898 end
899 print "\t{total}\t{holes}"
900
901 print "# size of attributes tables"
902 print "\ttotal \tholes"
903 total = 0
904 holes = 0
905 for t, table in attr_tables do
906 total += table.length
907 for e in table do if e == null then holes += 1
908 end
909 print "\t{total}\t{holes}"
910 end
911
912 redef fun compile_nitni_structs
913 do
914 self.header.add_decl("struct nitni_instance \{struct instance *value;\};")
915 end
916
917 redef fun finalize_ffi_for_module(nmodule)
918 do
919 var old_module = self.mainmodule
920 self.mainmodule = nmodule.mmodule.as(not null)
921 super
922 self.mainmodule = old_module
923 end
924 end
925
926 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
927 class SeparateCompilerVisitor
928 super AbstractCompilerVisitor
929
930 redef type COMPILER: SeparateCompiler
931
932 redef fun adapt_signature(m, args)
933 do
934 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
935 var recv = args.first
936 if recv.mtype.ctype != m.mclassdef.mclass.mclass_type.ctype then
937 args.first = self.autobox(args.first, m.mclassdef.mclass.mclass_type)
938 end
939 for i in [0..msignature.arity[ do
940 var t = msignature.mparameters[i].mtype
941 if i == msignature.vararg_rank then
942 t = args[i+1].mtype
943 end
944 args[i+1] = self.autobox(args[i+1], t)
945 end
946 end
947
948 redef fun autobox(value, mtype)
949 do
950 if value.mtype == mtype then
951 return value
952 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
953 return value
954 else if value.mtype.ctype == "val*" then
955 return self.new_expr("((struct instance_{mtype.c_instance_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
956 else if mtype.ctype == "val*" then
957 var valtype = value.mtype.as(MClassType)
958 var res = self.new_var(mtype)
959 if compiler.runtime_type_analysis != null and not compiler.runtime_type_analysis.live_types.has(valtype) then
960 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
961 self.add("printf(\"Dead code executed!\\n\"); show_backtrace(1);")
962 return res
963 end
964 self.require_declaration("BOX_{valtype.c_name}")
965 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
966 return res
967 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
968 return value
969 else
970 # Bad things will appen!
971 var res = self.new_var(mtype)
972 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
973 self.add("printf(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); show_backtrace(1);")
974 return res
975 end
976 end
977
978 # Return a C expression returning the runtime type structure of the value
979 # The point of the method is to works also with primitives types.
980 fun type_info(value: RuntimeVariable): String
981 do
982 if value.mtype.ctype == "val*" then
983 return "{value}->type"
984 else
985 compiler.undead_types.add(value.mtype)
986 self.require_declaration("type_{value.mtype.c_name}")
987 return "(&type_{value.mtype.c_name})"
988 end
989 end
990
991 redef fun send(mmethod, arguments)
992 do
993 self.varargize(mmethod.intro, mmethod.intro.msignature.as(not null), arguments)
994
995 if arguments.first.mcasttype.ctype != "val*" then
996 # In order to shortcut the primitive, we need to find the most specific method
997 # Howverr, because of performance (no flattening), we always work on the realmainmodule
998 var m = self.compiler.mainmodule
999 self.compiler.mainmodule = self.compiler.realmainmodule
1000 var res = self.monomorphic_send(mmethod, arguments.first.mcasttype, arguments)
1001 self.compiler.mainmodule = m
1002 return res
1003 end
1004
1005 return table_send(mmethod, arguments, mmethod.const_color)
1006 end
1007
1008 private fun table_send(mmethod: MMethod, arguments: Array[RuntimeVariable], const_color: String): nullable RuntimeVariable
1009 do
1010 assert arguments.length == mmethod.intro.msignature.arity + 1 else debug("Invalid arity for {mmethod}. {arguments.length} arguments given.")
1011
1012 var res: nullable RuntimeVariable
1013 var msignature = mmethod.intro.msignature.resolve_for(mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.mmodule, true)
1014 var ret = msignature.return_mtype
1015 if mmethod.is_new then
1016 ret = arguments.first.mtype
1017 res = self.new_var(ret)
1018 else if ret == null then
1019 res = null
1020 else
1021 res = self.new_var(ret)
1022 end
1023
1024 var s = new FlatBuffer
1025 var ss = new FlatBuffer
1026
1027 var recv = arguments.first
1028 s.append("val*")
1029 ss.append("{recv}")
1030 for i in [0..msignature.arity[ do
1031 var a = arguments[i+1]
1032 var t = msignature.mparameters[i].mtype
1033 if i == msignature.vararg_rank then
1034 t = arguments[i+1].mcasttype
1035 end
1036 s.append(", {t.ctype}")
1037 a = self.autobox(a, t)
1038 ss.append(", {a}")
1039 end
1040
1041 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or mmethod.name == "==" or mmethod.name == "!="
1042 var maybenull = recv.mcasttype isa MNullableType and consider_null
1043 if maybenull then
1044 self.add("if ({recv} == NULL) \{")
1045 if mmethod.name == "==" then
1046 assert res != null
1047 var arg = arguments[1]
1048 if arg.mcasttype isa MNullableType then
1049 self.add("{res} = ({arg} == NULL);")
1050 else if arg.mcasttype isa MNullType then
1051 self.add("{res} = 1; /* is null */")
1052 else
1053 self.add("{res} = 0; /* {arg.inspect} cannot be null */")
1054 end
1055 else if mmethod.name == "!=" then
1056 assert res != null
1057 var arg = arguments[1]
1058 if arg.mcasttype isa MNullableType then
1059 self.add("{res} = ({arg} != NULL);")
1060 else if arg.mcasttype isa MNullType then
1061 self.add("{res} = 0; /* is null */")
1062 else
1063 self.add("{res} = 1; /* {arg.inspect} cannot be null */")
1064 end
1065 else
1066 self.add_abort("Receiver is null")
1067 end
1068 self.add("\} else \{")
1069 end
1070 if not self.compiler.modelbuilder.toolcontext.opt_no_shortcut_equate.value and (mmethod.name == "==" or mmethod.name == "!=") then
1071 assert res != null
1072 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
1073 var arg = arguments[1]
1074 if arg.mcasttype isa MNullType then
1075 if mmethod.name == "==" then
1076 self.add("{res} = 0; /* arg is null but recv is not */")
1077 else
1078 self.add("{res} = 1; /* arg is null and recv is not */")
1079 end
1080 if maybenull then
1081 self.add("\}")
1082 end
1083 return res
1084 end
1085 end
1086
1087 var r
1088 if ret == null then r = "void" else r = ret.ctype
1089 self.require_declaration(const_color)
1090 var call = "(({r} (*)({s}))({arguments.first}->class->vft[{const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1091
1092 if res != null then
1093 self.add("{res} = {call};")
1094 else
1095 self.add("{call};")
1096 end
1097
1098 if maybenull then
1099 self.add("\}")
1100 end
1101
1102 return res
1103 end
1104
1105 redef fun call(mmethoddef, recvtype, arguments)
1106 do
1107 assert arguments.length == mmethoddef.msignature.arity + 1 else debug("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1108
1109 var res: nullable RuntimeVariable
1110 var ret = mmethoddef.msignature.return_mtype
1111 if mmethoddef.mproperty.is_new then
1112 ret = arguments.first.mtype
1113 res = self.new_var(ret)
1114 else if ret == null then
1115 res = null
1116 else
1117 ret = ret.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1118 res = self.new_var(ret)
1119 end
1120
1121 if self.compiler.modelbuilder.mpropdef2npropdef.has_key(mmethoddef) and
1122 self.compiler.modelbuilder.mpropdef2npropdef[mmethoddef] isa AInternMethPropdef and
1123 not compiler.modelbuilder.toolcontext.opt_no_inline_intern.value then
1124 var frame = new Frame(self, mmethoddef, recvtype, arguments)
1125 frame.returnlabel = self.get_name("RET_LABEL")
1126 frame.returnvar = res
1127 var old_frame = self.frame
1128 self.frame = frame
1129 self.add("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1130 mmethoddef.compile_inside_to_c(self, arguments)
1131 self.add("{frame.returnlabel.as(not null)}:(void)0;")
1132 self.add("\}")
1133 self.frame = old_frame
1134 return res
1135 end
1136
1137 # Autobox arguments
1138 self.adapt_signature(mmethoddef, arguments)
1139
1140 self.require_declaration(mmethoddef.c_name)
1141 if res == null then
1142 self.add("{mmethoddef.c_name}({arguments.join(", ")});")
1143 return null
1144 else
1145 self.add("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1146 end
1147
1148 return res
1149 end
1150
1151 redef fun supercall(m: MMethodDef, recvtype: MClassType, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1152 do
1153 if arguments.first.mcasttype.ctype != "val*" then
1154 # In order to shortcut the primitive, we need to find the most specific method
1155 # However, because of performance (no flattening), we always work on the realmainmodule
1156 var main = self.compiler.mainmodule
1157 self.compiler.mainmodule = self.compiler.realmainmodule
1158 var res = self.monomorphic_super_send(m, recvtype, arguments)
1159 self.compiler.mainmodule = main
1160 return res
1161 end
1162 return table_send(m.mproperty, arguments, m.const_color)
1163 end
1164
1165 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
1166 do
1167 # A vararg must be stored into an new array
1168 # The trick is that the dymaic type of the array may depends on the receiver
1169 # of the method (ie recv) if the static type is unresolved
1170 # This is more complex than usual because the unresolved type must not be resolved
1171 # with the current receiver (ie self).
1172 # Therefore to isolate the resolution from self, a local Frame is created.
1173 # One can see this implementation as an inlined method of the receiver whose only
1174 # job is to allocate the array
1175 var old_frame = self.frame
1176 var frame = new Frame(self, mpropdef, mpropdef.mclassdef.bound_mtype, [recv])
1177 self.frame = frame
1178 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1179 var res = self.array_instance(varargs, elttype)
1180 self.frame = old_frame
1181 return res
1182 end
1183
1184 redef fun isset_attribute(a, recv)
1185 do
1186 self.check_recv_notnull(recv)
1187 var res = self.new_var(bool_type)
1188
1189 # What is the declared type of the attribute?
1190 var mtype = a.intro.static_mtype.as(not null)
1191 var intromclassdef = a.intro.mclassdef
1192 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1193
1194 if mtype isa MNullableType then
1195 self.add("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1196 return res
1197 end
1198
1199 self.require_declaration(a.const_color)
1200 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1201 self.add("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1202 else
1203
1204 if mtype.ctype == "val*" then
1205 self.add("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1206 else
1207 self.add("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1208 end
1209 end
1210 return res
1211 end
1212
1213 redef fun read_attribute(a, recv)
1214 do
1215 self.check_recv_notnull(recv)
1216
1217 # What is the declared type of the attribute?
1218 var ret = a.intro.static_mtype.as(not null)
1219 var intromclassdef = a.intro.mclassdef
1220 ret = ret.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1221
1222 self.require_declaration(a.const_color)
1223 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1224 # Get the attribute or a box (ie. always a val*)
1225 var cret = self.object_type.as_nullable
1226 var res = self.new_var(cret)
1227 res.mcasttype = ret
1228
1229 self.add("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1230
1231 # Check for Uninitialized attribute
1232 if not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1233 self.add("if ({res} == NULL) \{")
1234 self.add_abort("Uninitialized attribute {a.name}")
1235 self.add("\}")
1236 end
1237
1238 # Return the attribute or its unboxed version
1239 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1240 return self.autobox(res, ret)
1241 else
1242 var res = self.new_var(ret)
1243 self.add("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1244
1245 # Check for Uninitialized attribute
1246 if ret.ctype == "val*" and not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1247 self.add("if ({res} == NULL) \{")
1248 self.add_abort("Uninitialized attribute {a.name}")
1249 self.add("\}")
1250 end
1251
1252 return res
1253 end
1254 end
1255
1256 redef fun write_attribute(a, recv, value)
1257 do
1258 self.check_recv_notnull(recv)
1259
1260 # What is the declared type of the attribute?
1261 var mtype = a.intro.static_mtype.as(not null)
1262 var intromclassdef = a.intro.mclassdef
1263 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1264
1265 # Adapt the value to the declared type
1266 value = self.autobox(value, mtype)
1267
1268 self.require_declaration(a.const_color)
1269 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1270 var attr = "{recv}->attrs[{a.const_color}]"
1271 if mtype.ctype != "val*" then
1272 assert mtype isa MClassType
1273 # The attribute is primitive, thus we store it in a box
1274 # The trick is to create the box the first time then resuse the box
1275 self.add("if ({attr} != NULL) \{")
1276 self.add("((struct instance_{mtype.c_instance_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1277 self.add("\} else \{")
1278 value = self.autobox(value, self.object_type.as_nullable)
1279 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1280 self.add("\}")
1281 else
1282 # The attribute is not primitive, thus store it direclty
1283 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1284 end
1285 else
1286 self.add("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1287 end
1288 end
1289
1290 # Check that mtype is a live open type
1291 fun hardening_live_open_type(mtype: MType)
1292 do
1293 if not compiler.modelbuilder.toolcontext.opt_hardening.value then return
1294 self.require_declaration(mtype.const_color)
1295 var col = mtype.const_color
1296 self.add("if({col} == -1) \{")
1297 self.add("fprintf(stderr, \"Resolution of a dead open type: %s\\n\", \"{mtype.to_s.escape_to_c}\");")
1298 self.add_abort("open type dead")
1299 self.add("\}")
1300 end
1301
1302 # Check that mtype it a pointer to a live cast type
1303 fun hardening_cast_type(t: String)
1304 do
1305 if not compiler.modelbuilder.toolcontext.opt_hardening.value then return
1306 add("if({t} == NULL) \{")
1307 add_abort("cast type null")
1308 add("\}")
1309 add("if({t}->id == -1 || {t}->color == -1) \{")
1310 add("fprintf(stderr, \"Try to cast on a dead cast type: %s\\n\", {t}->name);")
1311 add_abort("cast type dead")
1312 add("\}")
1313 end
1314
1315 redef fun init_instance(mtype)
1316 do
1317 self.require_declaration("NEW_{mtype.mclass.c_name}")
1318 var compiler = self.compiler
1319 if mtype isa MGenericType and mtype.need_anchor then
1320 hardening_live_open_type(mtype)
1321 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1322 var recv = self.frame.arguments.first
1323 var recv_type_info = self.type_info(recv)
1324 self.require_declaration(mtype.const_color)
1325 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1326 return self.new_expr("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1327 else
1328 return self.new_expr("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1329 end
1330 end
1331 compiler.undead_types.add(mtype)
1332 self.require_declaration("type_{mtype.c_name}")
1333 return self.new_expr("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype)
1334 end
1335
1336 redef fun type_test(value, mtype, tag)
1337 do
1338 self.add("/* {value.inspect} isa {mtype} */")
1339 var compiler = self.compiler
1340
1341 var recv = self.frame.arguments.first
1342 var recv_type_info = self.type_info(recv)
1343
1344 var res = self.new_var(bool_type)
1345
1346 var cltype = self.get_name("cltype")
1347 self.add_decl("int {cltype};")
1348 var idtype = self.get_name("idtype")
1349 self.add_decl("int {idtype};")
1350
1351 var maybe_null = self.maybe_null(value)
1352 var accept_null = "0"
1353 var ntype = mtype
1354 if ntype isa MNullableType then
1355 ntype = ntype.mtype
1356 accept_null = "1"
1357 end
1358
1359 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
1360 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1361 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1362 self.compiler.count_type_test_skipped[tag] += 1
1363 self.add("count_type_test_skipped_{tag}++;")
1364 end
1365 return res
1366 end
1367
1368 if ntype.need_anchor then
1369 var type_struct = self.get_name("type_struct")
1370 self.add_decl("const struct type* {type_struct};")
1371
1372 # Either with resolution_table with a direct resolution
1373 hardening_live_open_type(mtype)
1374 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1375 self.require_declaration(mtype.const_color)
1376 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1377 self.add("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})];")
1378 else
1379 self.add("{type_struct} = {recv_type_info}->resolution_table->types[{mtype.const_color}];")
1380 end
1381 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1382 self.compiler.count_type_test_unresolved[tag] += 1
1383 self.add("count_type_test_unresolved_{tag}++;")
1384 end
1385 hardening_cast_type(type_struct)
1386 self.add("{cltype} = {type_struct}->color;")
1387 self.add("{idtype} = {type_struct}->id;")
1388 if maybe_null and accept_null == "0" then
1389 var is_nullable = self.get_name("is_nullable")
1390 self.add_decl("short int {is_nullable};")
1391 self.add("{is_nullable} = {type_struct}->is_nullable;")
1392 accept_null = is_nullable.to_s
1393 end
1394 else if ntype isa MClassType then
1395 compiler.undead_types.add(mtype)
1396 self.require_declaration("type_{mtype.c_name}")
1397 hardening_cast_type("(&type_{mtype.c_name})")
1398 self.add("{cltype} = type_{mtype.c_name}.color;")
1399 self.add("{idtype} = type_{mtype.c_name}.id;")
1400 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1401 self.compiler.count_type_test_resolved[tag] += 1
1402 self.add("count_type_test_resolved_{tag}++;")
1403 end
1404 else
1405 self.add("printf(\"NOT YET IMPLEMENTED: type_test(%s, {mtype}).\\n\", \"{value.inspect}\"); show_backtrace(1);")
1406 end
1407
1408 # check color is in table
1409 if maybe_null then
1410 self.add("if({value} == NULL) \{")
1411 self.add("{res} = {accept_null};")
1412 self.add("\} else \{")
1413 end
1414 var value_type_info = self.type_info(value)
1415 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1416 self.add("{cltype} = HASH({value_type_info}->color, {idtype});")
1417 end
1418 self.add("if({cltype} >= {value_type_info}->table_size) \{")
1419 self.add("{res} = 0;")
1420 self.add("\} else \{")
1421 self.add("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1422 self.add("\}")
1423 if maybe_null then
1424 self.add("\}")
1425 end
1426
1427 return res
1428 end
1429
1430 redef fun is_same_type_test(value1, value2)
1431 do
1432 var res = self.new_var(bool_type)
1433 # Swap values to be symetric
1434 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1435 var tmp = value1
1436 value1 = value2
1437 value2 = tmp
1438 end
1439 if value1.mtype.ctype != "val*" then
1440 if value2.mtype == value1.mtype then
1441 self.add("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1442 else if value2.mtype.ctype != "val*" then
1443 self.add("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1444 else
1445 var mtype1 = value1.mtype.as(MClassType)
1446 self.require_declaration("class_{mtype1.c_name}")
1447 self.add("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1448 end
1449 else
1450 self.add("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1451 end
1452 return res
1453 end
1454
1455 redef fun class_name_string(value)
1456 do
1457 var res = self.get_name("var_class_name")
1458 self.add_decl("const char* {res};")
1459 if value.mtype.ctype == "val*" then
1460 self.add "{res} = {value} == NULL ? \"null\" : {value}->type->name;"
1461 else if value.mtype isa MClassType and value.mtype.as(MClassType).mclass.kind == extern_kind then
1462 self.add "{res} = \"{value.mtype.as(MClassType).mclass}\";"
1463 else
1464 self.require_declaration("type_{value.mtype.c_name}")
1465 self.add "{res} = type_{value.mtype.c_name}.name;"
1466 end
1467 return res
1468 end
1469
1470 redef fun equal_test(value1, value2)
1471 do
1472 var res = self.new_var(bool_type)
1473 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1474 var tmp = value1
1475 value1 = value2
1476 value2 = tmp
1477 end
1478 if value1.mtype.ctype != "val*" then
1479 if value2.mtype == value1.mtype then
1480 self.add("{res} = {value1} == {value2};")
1481 else if value2.mtype.ctype != "val*" then
1482 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1483 else
1484 var mtype1 = value1.mtype.as(MClassType)
1485 self.require_declaration("class_{mtype1.c_name}")
1486 self.add("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1487 self.add("if ({res}) \{")
1488 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1489 self.add("\}")
1490 end
1491 return res
1492 end
1493 var maybe_null = true
1494 var test = new Array[String]
1495 var t1 = value1.mcasttype
1496 if t1 isa MNullableType then
1497 test.add("{value1} != NULL")
1498 t1 = t1.mtype
1499 else
1500 maybe_null = false
1501 end
1502 var t2 = value2.mcasttype
1503 if t2 isa MNullableType then
1504 test.add("{value2} != NULL")
1505 t2 = t2.mtype
1506 else
1507 maybe_null = false
1508 end
1509
1510 var incompatible = false
1511 var primitive
1512 if t1.ctype != "val*" then
1513 primitive = t1
1514 if t1 == t2 then
1515 # No need to compare class
1516 else if t2.ctype != "val*" then
1517 incompatible = true
1518 else if can_be_primitive(value2) then
1519 test.add("{value1}->class == {value2}->class")
1520 else
1521 incompatible = true
1522 end
1523 else if t2.ctype != "val*" then
1524 primitive = t2
1525 if can_be_primitive(value1) then
1526 test.add("{value1}->class == {value2}->class")
1527 else
1528 incompatible = true
1529 end
1530 else
1531 primitive = null
1532 end
1533
1534 if incompatible then
1535 if maybe_null then
1536 self.add("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1537 return res
1538 else
1539 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1540 return res
1541 end
1542 end
1543 if primitive != null then
1544 test.add("((struct instance_{primitive.c_instance_name}*){value1})->value == ((struct instance_{primitive.c_instance_name}*){value2})->value")
1545 else if can_be_primitive(value1) and can_be_primitive(value2) then
1546 test.add("{value1}->class == {value2}->class")
1547 var s = new Array[String]
1548 for t, v in self.compiler.box_kinds do
1549 s.add "({value1}->class->box_kind == {v} && ((struct instance_{t.c_instance_name}*){value1})->value == ((struct instance_{t.c_instance_name}*){value2})->value)"
1550 end
1551 test.add("({s.join(" || ")})")
1552 else
1553 self.add("{res} = {value1} == {value2};")
1554 return res
1555 end
1556 self.add("{res} = {value1} == {value2} || ({test.join(" && ")});")
1557 return res
1558 end
1559
1560 fun can_be_primitive(value: RuntimeVariable): Bool
1561 do
1562 var t = value.mcasttype
1563 if t isa MNullableType then t = t.mtype
1564 if not t isa MClassType then return false
1565 var k = t.mclass.kind
1566 return k == interface_kind or t.ctype != "val*"
1567 end
1568
1569 fun maybe_null(value: RuntimeVariable): Bool
1570 do
1571 var t = value.mcasttype
1572 return t isa MNullableType or t isa MNullType
1573 end
1574
1575 redef fun array_instance(array, elttype)
1576 do
1577 var nclass = self.get_class("NativeArray")
1578 var arrayclass = self.get_class("Array")
1579 var arraytype = arrayclass.get_mtype([elttype])
1580 var res = self.init_instance(arraytype)
1581 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
1582 var length = self.int_instance(array.length)
1583 var nat = native_array_instance(elttype, length)
1584 for i in [0..array.length[ do
1585 var r = self.autobox(array[i], self.object_type)
1586 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1587 end
1588 self.send(self.get_property("with_native", arrayclass.intro.bound_mtype), [res, nat, length])
1589 self.add("\}")
1590 return res
1591 end
1592
1593 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
1594 do
1595 var mtype = self.get_class("NativeArray").get_mtype([elttype])
1596 self.require_declaration("NEW_{mtype.mclass.c_name}")
1597 assert mtype isa MGenericType
1598 var compiler = self.compiler
1599 if mtype.need_anchor then
1600 hardening_live_open_type(mtype)
1601 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1602 var recv = self.frame.arguments.first
1603 var recv_type_info = self.type_info(recv)
1604 self.require_declaration(mtype.const_color)
1605 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1606 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1607 else
1608 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1609 end
1610 end
1611 compiler.undead_types.add(mtype)
1612 self.require_declaration("type_{mtype.c_name}")
1613 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype)
1614 end
1615
1616 redef fun native_array_def(pname, ret_type, arguments)
1617 do
1618 var elttype = arguments.first.mtype
1619 var nclass = self.get_class("NativeArray")
1620 var recv = "((struct instance_{nclass.c_instance_name}*){arguments[0]})->values"
1621 if pname == "[]" then
1622 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
1623 return
1624 else if pname == "[]=" then
1625 self.add("{recv}[{arguments[1]}]={arguments[2]};")
1626 return
1627 else if pname == "copy_to" then
1628 var recv1 = "((struct instance_{nclass.c_instance_name}*){arguments[1]})->values"
1629 self.add("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1630 return
1631 end
1632 end
1633
1634 redef fun calloc_array(ret_type, arguments)
1635 do
1636 var mclass = self.get_class("ArrayCapable")
1637 var ft = mclass.mclass_type.arguments.first.as(MParameterType)
1638 var res = self.native_array_instance(ft, arguments[1])
1639 self.ret(res)
1640 end
1641
1642 fun link_unresolved_type(mclassdef: MClassDef, mtype: MType) do
1643 assert mtype.need_anchor
1644 var compiler = self.compiler
1645 if not compiler.live_unresolved_types.has_key(self.frame.mpropdef.mclassdef) then
1646 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef] = new HashSet[MType]
1647 end
1648 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef].add(mtype)
1649 end
1650 end
1651
1652 redef class MMethodDef
1653 fun separate_runtime_function: AbstractRuntimeFunction
1654 do
1655 var res = self.separate_runtime_function_cache
1656 if res == null then
1657 res = new SeparateRuntimeFunction(self)
1658 self.separate_runtime_function_cache = res
1659 end
1660 return res
1661 end
1662 private var separate_runtime_function_cache: nullable SeparateRuntimeFunction
1663
1664 fun virtual_runtime_function: AbstractRuntimeFunction
1665 do
1666 var res = self.virtual_runtime_function_cache
1667 if res == null then
1668 res = new VirtualRuntimeFunction(self)
1669 self.virtual_runtime_function_cache = res
1670 end
1671 return res
1672 end
1673 private var virtual_runtime_function_cache: nullable VirtualRuntimeFunction
1674 end
1675
1676 # The C function associated to a methoddef separately compiled
1677 class SeparateRuntimeFunction
1678 super AbstractRuntimeFunction
1679
1680 redef fun build_c_name: String do return "{mmethoddef.c_name}"
1681
1682 redef fun to_s do return self.mmethoddef.to_s
1683
1684 redef fun compile_to_c(compiler)
1685 do
1686 var mmethoddef = self.mmethoddef
1687
1688 var recv = self.mmethoddef.mclassdef.bound_mtype
1689 var v = compiler.new_visitor
1690 var selfvar = new RuntimeVariable("self", recv, recv)
1691 var arguments = new Array[RuntimeVariable]
1692 var frame = new Frame(v, mmethoddef, recv, arguments)
1693 v.frame = frame
1694
1695 var msignature = mmethoddef.msignature.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1696
1697 var sig = new FlatBuffer
1698 var comment = new FlatBuffer
1699 var ret = msignature.return_mtype
1700 if ret != null then
1701 sig.append("{ret.ctype} ")
1702 else if mmethoddef.mproperty.is_new then
1703 ret = recv
1704 sig.append("{ret.ctype} ")
1705 else
1706 sig.append("void ")
1707 end
1708 sig.append(self.c_name)
1709 sig.append("({selfvar.mtype.ctype} {selfvar}")
1710 comment.append("({selfvar}: {selfvar.mtype}")
1711 arguments.add(selfvar)
1712 for i in [0..msignature.arity[ do
1713 var mtype = msignature.mparameters[i].mtype
1714 if i == msignature.vararg_rank then
1715 mtype = v.get_class("Array").get_mtype([mtype])
1716 end
1717 comment.append(", {mtype}")
1718 sig.append(", {mtype.ctype} p{i}")
1719 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1720 arguments.add(argvar)
1721 end
1722 sig.append(")")
1723 comment.append(")")
1724 if ret != null then
1725 comment.append(": {ret}")
1726 end
1727 compiler.provide_declaration(self.c_name, "{sig};")
1728
1729 v.add_decl("/* method {self} for {comment} */")
1730 v.add_decl("{sig} \{")
1731 if ret != null then
1732 frame.returnvar = v.new_var(ret)
1733 end
1734 frame.returnlabel = v.get_name("RET_LABEL")
1735
1736 if recv != arguments.first.mtype then
1737 #print "{self} {recv} {arguments.first}"
1738 end
1739 mmethoddef.compile_inside_to_c(v, arguments)
1740
1741 v.add("{frame.returnlabel.as(not null)}:;")
1742 if ret != null then
1743 v.add("return {frame.returnvar.as(not null)};")
1744 end
1745 v.add("\}")
1746 if not self.c_name.has_substring("VIRTUAL", 0) then compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1747 end
1748 end
1749
1750 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1751 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1752 class VirtualRuntimeFunction
1753 super AbstractRuntimeFunction
1754
1755 redef fun build_c_name: String do return "VIRTUAL_{mmethoddef.c_name}"
1756
1757 redef fun to_s do return self.mmethoddef.to_s
1758
1759 redef fun compile_to_c(compiler)
1760 do
1761 var mmethoddef = self.mmethoddef
1762
1763 var recv = self.mmethoddef.mclassdef.bound_mtype
1764 var v = compiler.new_visitor
1765 var selfvar = new RuntimeVariable("self", v.object_type, recv)
1766 var arguments = new Array[RuntimeVariable]
1767 var frame = new Frame(v, mmethoddef, recv, arguments)
1768 v.frame = frame
1769
1770 var sig = new FlatBuffer
1771 var comment = new FlatBuffer
1772
1773 # Because the function is virtual, the signature must match the one of the original class
1774 var intromclassdef = self.mmethoddef.mproperty.intro.mclassdef
1775 var msignature = mmethoddef.mproperty.intro.msignature.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1776 var ret = msignature.return_mtype
1777 if ret != null then
1778 sig.append("{ret.ctype} ")
1779 else if mmethoddef.mproperty.is_new then
1780 ret = recv
1781 sig.append("{ret.ctype} ")
1782 else
1783 sig.append("void ")
1784 end
1785 sig.append(self.c_name)
1786 sig.append("({selfvar.mtype.ctype} {selfvar}")
1787 comment.append("({selfvar}: {selfvar.mtype}")
1788 arguments.add(selfvar)
1789 for i in [0..msignature.arity[ do
1790 var mtype = msignature.mparameters[i].mtype
1791 if i == msignature.vararg_rank then
1792 mtype = v.get_class("Array").get_mtype([mtype])
1793 end
1794 comment.append(", {mtype}")
1795 sig.append(", {mtype.ctype} p{i}")
1796 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1797 arguments.add(argvar)
1798 end
1799 sig.append(")")
1800 comment.append(")")
1801 if ret != null then
1802 comment.append(": {ret}")
1803 end
1804 compiler.provide_declaration(self.c_name, "{sig};")
1805
1806 v.add_decl("/* method {self} for {comment} */")
1807 v.add_decl("{sig} \{")
1808 if ret != null then
1809 frame.returnvar = v.new_var(ret)
1810 end
1811 frame.returnlabel = v.get_name("RET_LABEL")
1812
1813 var subret = v.call(mmethoddef, recv, arguments)
1814 if ret != null then
1815 assert subret != null
1816 v.assign(frame.returnvar.as(not null), subret)
1817 end
1818
1819 v.add("{frame.returnlabel.as(not null)}:;")
1820 if ret != null then
1821 v.add("return {frame.returnvar.as(not null)};")
1822 end
1823 v.add("\}")
1824 if not self.c_name.has_substring("VIRTUAL", 0) then compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}--{mmethoddef.location.line_start})"
1825 end
1826
1827 # TODO ?
1828 redef fun call(v, arguments) do abort
1829 end
1830
1831 redef class MType
1832 fun const_color: String do return "COLOR_{c_name}"
1833
1834 # C name of the instance type to use
1835 fun c_instance_name: String do return c_name
1836 end
1837
1838 redef class MClassType
1839 redef fun c_instance_name do return mclass.c_instance_name
1840 end
1841
1842 redef class MClass
1843 # Extern classes use the C instance of kernel::Pointer
1844 fun c_instance_name: String
1845 do
1846 if kind == extern_kind then
1847 return "kernel__Pointer"
1848 else return c_name
1849 end
1850 end
1851
1852 redef class MProperty
1853 fun const_color: String do return "COLOR_{c_name}"
1854 end
1855
1856 redef class MPropDef
1857 fun const_color: String do return "COLOR_{c_name}"
1858 end