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