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