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