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