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