31bd86b98597d0077d43d2ecc6ec7aa32ede4229
[nit.git] / src / compiling / compiling_global.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Compute and generate tables for classes and modules.
18 package compiling_global
19
20 #import compiling_base
21 private import compiling_methods
22 private import syntax
23
24 # Something that store color of table elements
25 class ColorContext
26 var _colors: HashMap[TableElt, Int] = new HashMap[TableElt, Int]
27
28 # The color of a table element.
29 fun color(e: TableElt): Int
30 do
31 return _colors[e]
32 end
33
34 # Is a table element already colored?
35 fun has_color(e: TableElt): Bool
36 do
37 return _colors.has_key(e)
38 end
39
40 # Assign a color to a table element.
41 fun color=(e: TableElt, c: Int)
42 do
43 _colors[e] = c
44 var idx = c
45 for i in [0..e.length[ do
46 _colors[e.item(i)] = idx
47 idx = idx + 1
48 end
49 end
50 end
51
52 # All information and results of the global analysis.
53 class GlobalAnalysis
54 special ColorContext
55 # Associate global classes to compiled classes
56 readable var _compiled_classes: HashMap[MMGlobalClass, CompiledClass] = new HashMap[MMGlobalClass, CompiledClass]
57
58 # The main module of the program globally analysed
59 readable var _module: MMModule
60
61 # FIXME: do something better.
62 readable writable var _max_class_table_length: Int = 0
63
64 init(module: MMModule)
65 do
66 _module = module
67 end
68 end
69
70 class GlobalCompilerVisitor
71 special CompilerVisitor
72 # The global analysis result
73 readable var _global_analysis: GlobalAnalysis
74 init(m: MMModule, tc: ToolContext, ga: GlobalAnalysis)
75 do
76 super(m, tc)
77 _global_analysis = ga
78 end
79 end
80
81 # A compiled class is a class in a program
82 class CompiledClass
83 special ColorContext
84 # The corresponding local class in the main module of the prgram
85 readable var _local_class: MMLocalClass
86
87 # The identifier of the class
88 readable writable var _id: Int = 0
89
90 # The full class table of the class
91 readable var _class_table: Array[nullable TableElt] = new Array[nullable TableElt]
92
93 # The full instance table of the class
94 readable var _instance_table: Array[nullable TableElt] = new Array[nullable TableElt]
95
96 # The proper class table part (no superclasses but all refinements)
97 readable writable var _class_layout: TableEltComposite = new TableEltComposite(self)
98
99 # The proper instance table part (no superclasses but all refinements)
100 readable writable var _instance_layout: TableEltComposite = new TableEltComposite(self)
101
102 init(c: MMLocalClass) do _local_class = c
103 end
104
105 redef class MMConcreteClass
106 # The table element of the subtype check
107 fun class_color_pos: TableEltClassColor do return _class_color_pos.as(not null)
108 var _class_color_pos: nullable TableEltClassColor
109
110 # The proper local class table part (nor superclasses nor refinments)
111 readable var _class_layout: Array[TableElt] = new Array[TableElt]
112
113 # The proper local instance table part (nor superclasses nor refinments)
114 readable var _instance_layout: Array[TableElt] = new Array[TableElt]
115
116 # Build the local layout of the class and feed the module table
117 fun build_layout_in(tc: ToolContext, module_table: Array[ModuleTableElt])
118 do
119 var clt = _class_layout
120 var ilt = _instance_layout
121
122 if global.intro == self then
123 module_table.add(new TableEltClassId(self))
124 var cpp = new TableEltClassColor(self)
125 _class_color_pos = cpp
126 module_table.add(cpp)
127 clt.add(new TableEltClassInitTable(self))
128 end
129 for p in local_local_properties do
130 var pg = p.global
131 if pg.intro == p then
132 if p isa MMAttribute then
133 ilt.add(new TableEltAttr(p))
134 else if p isa MMMethod then
135 clt.add(new TableEltMeth(p))
136 end
137 end
138 if p isa MMMethod and p.need_super then
139 clt.add(new TableEltSuper(p))
140 end
141 end
142
143 if not ilt.is_empty then
144 var teg = new ModuleTableEltGroup
145 teg.elements.append(ilt)
146 module_table.add(teg)
147 end
148
149 if not clt.is_empty then
150 var teg = new ModuleTableEltGroup
151 teg.elements.append(clt)
152 module_table.add(teg)
153 end
154 end
155 end
156
157 redef class MMModule
158 # The local table of the module (refers things introduced in the module)
159 var _local_table: Array[ModuleTableElt] = new Array[ModuleTableElt]
160
161 # Builds the local tables and local classes layouts
162 fun local_analysis(tc: ToolContext)
163 do
164 for c in local_classes do
165 if c isa MMConcreteClass then
166 c.build_layout_in(tc, _local_table)
167 end
168 end
169 end
170
171 # Do the complete global analysis
172 fun global_analysis(cctx: ToolContext): GlobalAnalysis
173 do
174 #print "Do the complete global analysis"
175 var ga = new GlobalAnalysis(self)
176 var smallest_classes = new Array[MMLocalClass]
177 var global_properties = new HashSet[MMGlobalProperty]
178 var ctab = new Array[TableElt]
179 var itab = new Array[TableElt]
180
181 ctab.add(new TableEltClassSelfId)
182 itab.add(new TableEltVftPointer)
183
184 var pclassid = -1
185 var classid = 3
186
187 # We have to work on ALL the classes of the module
188 var classes = new Array[MMLocalClass]
189 for c in local_classes do
190 c.compute_super_classes
191 classes.add(c)
192 end
193 (new ClassSorter).sort(classes)
194
195 for c in classes do
196 # Finish processing the class (if invisible)
197 c.compute_ancestors
198 c.inherit_global_properties
199
200 # Associate a CompiledClass to the class
201 var cc = new CompiledClass(c)
202 ga.compiled_classes[c.global] = cc
203
204 # Assign a unique class identifier
205 # (negative are for primitive classes)
206 var gc = c.global
207 var bm = gc.module
208 if c.primitive_info != null then
209 cc.id = pclassid
210 pclassid = pclassid - 4
211 else
212 cc.id = classid
213 classid = classid + 4
214 end
215
216 # Register is the class is a leaf
217 if c.cshe.direct_smallers.is_empty then
218 smallest_classes.add(c)
219 end
220
221 # Store the colortableelt in the class table pool
222 var bc = c.global.intro
223 assert bc isa MMConcreteClass
224 ctab.add(bc.class_color_pos)
225 end
226
227 # Compute core and crown classes for colorization
228 var crown_classes = new HashSet[MMLocalClass]
229 var core_classes = new HashSet[MMLocalClass]
230 for c in smallest_classes do
231 while c.cshe.direct_greaters.length == 1 do
232 c = c.cshe.direct_greaters.first
233 end
234 crown_classes.add(c)
235 core_classes.add_all(c.cshe.greaters_and_self)
236 end
237 #print("nbclasses: {classes.length} leaves: {smallest_classes.length} crown: {crown_classes.length} core: {core_classes.length}")
238
239 # Colorize core color for typechecks
240 colorize(ga, ctab, crown_classes, 0)
241
242 # Compute tables for typechecks
243 var maxcolor = 0
244 for c in classes do
245 var cc = ga.compiled_classes[c.global]
246 if core_classes.has(c) then
247 # For core classes, just build the table
248 build_tables_in(cc.class_table, ga, c, ctab)
249 if maxcolor < cc.class_table.length then maxcolor = cc.class_table.length
250 else
251 # For other classes, it's easier: just append to the parent tables
252 var sc = c.cshe.direct_greaters.first
253 var scc = ga.compiled_classes[sc.global]
254 assert cc.class_table.is_empty
255 cc.class_table.add_all(scc.class_table)
256 var bc = c.global.intro
257 assert bc isa MMConcreteClass
258 var colpos = bc.class_color_pos
259 var colposcolor = cc.class_table.length
260 ga.color(colpos) = colposcolor
261 cc.class_table.add(colpos)
262 if maxcolor < colposcolor then maxcolor = colposcolor
263 end
264 end
265 ga.max_class_table_length = maxcolor + 1
266
267 # Fill class table and instance tables pools
268 for c in classes do
269 var cc = ga.compiled_classes[c.global]
270 var cte = cc.class_layout
271 var ite = cc.instance_layout
272 for sc in c.crhe.greaters_and_self do
273 if sc isa MMConcreteClass then
274 cte.add(sc, sc.class_layout)
275 ite.add(sc, sc.instance_layout)
276 end
277 end
278
279 if core_classes.has(c) then
280 if cte.length > 0 then
281 ctab.add(cte)
282 end
283 if ite.length > 0 then
284 itab.add(ite)
285 end
286 end
287 end
288
289 # Colorize all elements in pools tables
290 colorize(ga, ctab, crown_classes, maxcolor+1)
291 colorize(ga, itab, crown_classes, 0)
292
293 # Build class and instance tables now things are colored
294 ga.max_class_table_length = 0
295 for c in classes do
296 var cc = ga.compiled_classes[c.global]
297 if core_classes.has(c) then
298 # For core classes, just build the table
299 build_tables_in(cc.class_table, ga, c, ctab)
300 build_tables_in(cc.instance_table, ga, c, itab)
301 else
302 # For other classes, it's easier: just append to the parent tables
303 var sc = c.cshe.direct_greaters.first
304 var scc = ga.compiled_classes[sc.global]
305 cc.class_table.clear
306 cc.class_table.add_all(scc.class_table)
307 var bc = c.global.intro
308 assert bc isa MMConcreteClass
309 var colpos = bc.class_color_pos
310 cc.class_table[ga.color(colpos)] = colpos
311 while cc.class_table.length <= maxcolor do
312 cc.class_table.add(null)
313 end
314 append_to_table(ga, cc.class_table, cc.class_layout)
315 assert cc.instance_table.is_empty
316 cc.instance_table.add_all(scc.instance_table)
317 append_to_table(ga, cc.instance_table, cc.instance_layout)
318 end
319 end
320
321 return ga
322 end
323
324 private fun append_to_table(cc: ColorContext, table: Array[nullable TableElt], cmp: TableEltComposite)
325 do
326 for j in [0..cmp.length[ do
327 var e = cmp.item(j)
328 cc.color(e) = table.length
329 table.add(e)
330 end
331 end
332
333 private fun build_tables_in(table: Array[nullable TableElt], ga: GlobalAnalysis, c: MMLocalClass, elts: Array[TableElt])
334 do
335 var tab = new HashMap[Int, TableElt]
336 var len = 0
337 for e in elts do
338 if e.is_related_to(c) then
339 var col = ga.color(e)
340 var l = col + e.length
341 tab[col] = e
342 if len < l then
343 len = l
344 end
345 end
346 end
347 var i = 0
348 while i < len do
349 if tab.has_key(i) then
350 var e = tab[i]
351 for j in [0..e.length[ do
352 table[i] = e.item(j)
353 i = i + 1
354 end
355 else
356 table[i] = null
357 i = i + 1
358 end
359 end
360 end
361
362 # Perform coloring
363 fun colorize(ga: GlobalAnalysis, elts: Array[TableElt], classes: Collection[MMLocalClass], startcolor: Int)
364 do
365 var colors = new HashMap[Int, Array[TableElt]]
366 var rel_classes = new Array[MMLocalClass]
367 for e in elts do
368 var color = -1
369 var len = e.length
370 if ga.has_color(e) then
371 color = ga.color(e)
372 else
373 rel_classes.clear
374 for c in classes do
375 if e.is_related_to(c) then
376 rel_classes.add(c)
377 end
378 end
379 var trycolor = startcolor
380 while trycolor != color do
381 color = trycolor
382 for c in rel_classes do
383 var idx = 0
384 while idx < len do
385 if colors.has_key(trycolor + idx) and not free_color(colors[trycolor + idx], c) then
386 trycolor = trycolor + idx + 1
387 idx = 0
388 else
389 idx = idx + 1
390 end
391 end
392 end
393 end
394 ga.color(e) = color
395 end
396 for idx in [0..len[ do
397 if colors.has_key(color + idx) then
398 colors[color + idx].add(e)
399 else
400 colors[color + idx] = [e]
401 end
402 end
403 end
404 end
405
406 private fun free_color(es: Array[TableElt], c: MMLocalClass): Bool
407 do
408 for e2 in es do
409 if e2.is_related_to(c) then
410 return false
411 end
412 end
413 return true
414 end
415
416 # Compile module and class tables
417 fun compile_tables_to_c(v: GlobalCompilerVisitor)
418 do
419 for m in mhe.greaters_and_self do
420 m.compile_local_table_to_c(v)
421 end
422
423 for c in local_classes do
424 c.compile_tables_to_c(v)
425 end
426 var s = new Buffer.from("classtable_t TAG2VFT[4] = \{NULL")
427 for t in ["Int","Char","Bool"] do
428 if has_global_class_named(t.to_symbol) then
429 s.append(", (const classtable_t)VFT_{t}")
430 else
431 s.append(", NULL")
432 end
433 end
434 s.append("};")
435 v.add_instr(s.to_s)
436 end
437
438 # Declare class table (for _sep.h)
439 fun declare_class_tables_to_c(v: GlobalCompilerVisitor)
440 do
441 for c in local_classes do
442 if c.global.module == self then
443 c.declare_tables_to_c(v)
444 end
445 end
446 end
447
448 # Compile main part (for _table.c)
449 fun compile_main_part(v: GlobalCompilerVisitor)
450 do
451 v.add_instr("int main(int argc, char **argv) \{")
452 v.indent
453 v.add_instr("prepare_signals();")
454 v.add_instr("glob_argc = argc; glob_argv = argv;")
455 var sysname = once "Sys".to_symbol
456 if not has_global_class_named(sysname) then
457 print("No main")
458 else
459 var sys = class_by_name(sysname)
460 var name = once "main".to_symbol
461 if not sys.has_global_property_by_name(name) then
462 print("No main")
463 else
464 var mainm = sys.select_method(name)
465 v.add_instr("G_sys = NEW_Sys();")
466 v.add_instr("{mainm.cname}(G_sys);")
467 end
468 end
469 v.add_instr("return 0;")
470 v.unindent
471 v.add_instr("}")
472 end
473
474 # Compile sep files
475 fun compile_mod_to_c(v: GlobalCompilerVisitor)
476 do
477 v.add_decl("extern const char *LOCATE_{name};")
478 if not v.tc.global then
479 v.add_decl("extern const int SFT_{name}[];")
480 end
481 var i = 0
482 for e in _local_table do
483 var value: String
484 if v.tc.global then
485 value = "{e.value(v.global_analysis)}"
486 else
487 value = "SFT_{name}[{i}]"
488 i = i + 1
489 end
490 e.compile_macros(v, value)
491 end
492 for c in local_classes do
493 if not c isa MMConcreteClass then continue
494 for pg in c.global_properties do
495 var p = c[pg]
496 if p.local_class == c then
497 p.compile_property_to_c(v)
498 end
499 if pg.is_init_for(c) then
500 # Declare constructors
501 var params = new Array[String]
502 for i in [0..p.signature.arity[ do
503 params.add("val_t p{i}")
504 end
505 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
506 end
507 end
508 end
509 end
510
511 # Compile module file for the current module
512 fun compile_local_table_to_c(v: GlobalCompilerVisitor)
513 do
514 v.add_instr("const char *LOCATE_{name} = \"{location.file}\";")
515
516 if v.tc.global or _local_table.is_empty then
517 return
518 end
519
520 v.add_instr("const int SFT_{name}[{_local_table.length}] = \{")
521 v.indent
522 for e in _local_table do
523 v.add_instr(e.value(v.global_analysis) + ",")
524 end
525 v.unindent
526 v.add_instr("\};")
527 end
528 end
529
530 ###############################################################################
531
532 # An element of a class, an instance or a module table
533 abstract class AbsTableElt
534 # Compile the macro needed to use the element and other related elements
535 fun compile_macros(v: GlobalCompilerVisitor, value: String) is abstract
536 end
537
538 # An element of a class or an instance table
539 # Such an elements represent method function pointers, attribute values, etc.
540 abstract class TableElt
541 special AbsTableElt
542 # Is the element conflict to class `c' (used for coloring)
543 fun is_related_to(c: MMLocalClass): Bool is abstract
544
545 # Number of sub-elements. 1 if none
546 fun length: Int do return 1
547
548 # Access the ith subelement.
549 fun item(i: Int): TableElt do return self
550
551 # Return the value of the element for a given class
552 fun compile_to_c(v: GlobalCompilerVisitor, c: MMLocalClass): String is abstract
553 end
554
555 # An element of a module table
556 # Such an elements represent colors or identifiers
557 abstract class ModuleTableElt
558 special AbsTableElt
559 # Return the value of the element once the global analisys is performed
560 fun value(ga: GlobalAnalysis): String is abstract
561 end
562
563 # An element of a module table that represents a group of TableElt defined in the same local class
564 class ModuleTableEltGroup
565 special ModuleTableElt
566 readable var _elements: Array[TableElt] = new Array[TableElt]
567
568 redef fun value(ga) do return "{ga.color(_elements.first)} /* Group of ? */"
569 redef fun compile_macros(v, value)
570 do
571 var i = 0
572 for e in _elements do
573 e.compile_macros(v, "{value} + {i}")
574 i += 1
575 end
576 end
577 end
578
579 # An element that represents a class property
580 abstract class TableEltProp
581 special TableElt
582 var _property: MMLocalProperty
583
584 init(p: MMLocalProperty)
585 do
586 _property = p
587 end
588 end
589
590 # An element that represents a function pointer to a global method
591 class TableEltMeth
592 special TableEltProp
593 redef fun compile_macros(v, value)
594 do
595 var pg = _property.global
596 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
597 end
598
599 redef fun compile_to_c(v, c)
600 do
601 var p = c[_property.global]
602 return p.cname
603 end
604 end
605
606 # An element that represents a function pointer to the super method of a local method
607 class TableEltSuper
608 special TableEltProp
609 redef fun compile_macros(v, value)
610 do
611 var p = _property
612 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
613 end
614
615 redef fun compile_to_c(v, c)
616 do
617 var pc = _property.local_class
618 var g = _property.global
619 var lin = c.che.linear_extension
620 var found = false
621 for s in lin do
622 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
623 if s == pc then
624 found = true
625 else if found and c.che < s then
626 if s.has_global_property(g) then
627 #print "found {s.module}::{s}::{p}"
628 return s[g].cname
629 end
630 end
631 end
632 abort
633 end
634 end
635
636 # An element that represents the value stored for a global attribute
637 class TableEltAttr
638 special TableEltProp
639 redef fun compile_macros(v, value)
640 do
641 var pg = _property.global
642 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
643 end
644
645 redef fun compile_to_c(v, c)
646 do
647 var ga = v.global_analysis
648 var p = c[_property.global]
649 return "/* {ga.color(self)}: Attribute {c}::{p} */"
650 end
651 end
652
653 # An element representing a class information
654 class AbsTableEltClass
655 special AbsTableElt
656 # The local class where the information comes from
657 var _local_class: MMLocalClass
658
659 init(c: MMLocalClass)
660 do
661 _local_class = c
662 end
663
664 # The C macro name refering the value
665 fun symbol: String is abstract
666
667 redef fun compile_macros(v, value)
668 do
669 v.add_decl("#define {symbol} ({value})")
670 end
671 end
672
673 # An element of a class table representing a class information
674 class TableEltClass
675 special TableElt
676 special AbsTableEltClass
677 redef fun is_related_to(c)
678 do
679 var bc = c.module[_local_class.global]
680 return c.cshe <= bc
681 end
682 end
683
684 # An element representing the id of a class in a module table
685 class TableEltClassId
686 special ModuleTableElt
687 special AbsTableEltClass
688 redef fun symbol do return _local_class.global.id_id
689
690 redef fun value(ga)
691 do
692 return "{ga.compiled_classes[_local_class.global].id} /* Id of {_local_class} */"
693 end
694 end
695
696 # An element representing the constructor marker position in a class table
697 class TableEltClassInitTable
698 special TableEltClass
699 redef fun symbol do return _local_class.global.init_table_pos_id
700
701 redef fun compile_to_c(v, c)
702 do
703 var ga = v.global_analysis
704 var cc = ga.compiled_classes[_local_class.global]
705 var linext = c.cshe.reverse_linear_extension
706 var i = 0
707 while linext[i].global != _local_class.global do
708 i += 1
709 end
710 return "{i} /* {ga.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
711 end
712 end
713
714 # An element used for a cast
715 # Note: this element is both a TableElt and a ModuleTableElt.
716 # At the TableElt offset, there is the id of the super-class
717 # At the ModuleTableElt offset, there is the TableElt offset (ie. the color of the super-class).
718 class TableEltClassColor
719 special TableEltClass
720 special ModuleTableElt
721 redef fun symbol do return _local_class.global.color_id
722
723 redef fun value(ga)
724 do
725 return "{ga.color(self)} /* Color of {_local_class} */"
726 end
727
728 redef fun compile_to_c(v, c)
729 do
730 var ga = v.global_analysis
731 var cc = ga.compiled_classes[_local_class.global]
732 return "{cc.id} /* {ga.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
733 end
734 end
735
736 # A Group of elements introduced in the same global-class that are colored together
737 class TableEltComposite
738 special TableElt
739 var _table: Array[TableElt]
740 var _cc: CompiledClass
741 var _offsets: HashMap[MMLocalClass, Int]
742 redef fun length do return _table.length
743 redef fun is_related_to(c) do return c.cshe <= _cc.local_class
744
745 fun add(c: MMLocalClass, tab: Array[TableElt])
746 do
747 _offsets[c] = _table.length
748 _table.append(tab)
749 end
750
751 redef fun item(i) do return _table[i]
752
753 redef fun compile_to_c(v, c) do abort
754
755 init(cc: CompiledClass)
756 do
757 _cc = cc
758 _table = new Array[TableElt]
759 _offsets = new HashMap[MMLocalClass, Int]
760 end
761 end
762
763 # The element that represent the class id
764 class TableEltClassSelfId
765 special TableElt
766 redef fun is_related_to(c) do return true
767 redef fun compile_to_c(v, c)
768 do
769 var ga = v.global_analysis
770 return "{v.global_analysis.compiled_classes[c.global].id} /* {ga.color(self)}: Identity */"
771 end
772 end
773
774 # The element that
775 class TableEltVftPointer
776 special TableElt
777 redef fun is_related_to(c) do return true
778 redef fun compile_to_c(v, c)
779 do
780 var ga = v.global_analysis
781 return "/* {ga.color(self)}: Pointer to the classtable */"
782 end
783 end
784
785 ###############################################################################
786
787 # Used to sort local class in a deterministic total order
788 # The total order superset the class refinement and the class specialisation relations
789 class ClassSorter
790 special AbstractSorter[MMLocalClass]
791 redef fun compare(a, b) do return a.compare(b)
792 init do end
793 end
794
795 redef class MMLocalClass
796 # Comparaison in a total order that superset the class refinement and the class specialisation relations
797 fun compare(b: MMLocalClass): Int
798 do
799 var a = self
800 if a == b then
801 return 0
802 else if a.module.mhe < b.module then
803 return 1
804 else if b.module.mhe < a.module then
805 return -1
806 end
807 var ar = a.cshe.rank
808 var br = b.cshe.rank
809 if ar > br then
810 return 1
811 else if br > ar then
812 return -1
813 else
814 return b.name.to_s <=> a.name.to_s
815 end
816 end
817
818 # Declaration and macros related to the class table
819 fun declare_tables_to_c(v: GlobalCompilerVisitor)
820 do
821 v.add_decl("")
822 var pi = primitive_info
823 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
824 if pi == null then
825 # v.add_decl("val_t NEW_{name}(void);")
826 else if not pi.tagged then
827 var t = pi.cname
828 var tbox = "struct TBOX_{name}"
829 v.add_decl("{tbox} \{ const classtable_elt_t * vft; {t} val;};")
830 v.add_decl("val_t BOX_{name}({t} val);")
831 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
832 end
833 end
834
835 # Compilation of table and new (or box)
836 fun compile_tables_to_c(v: GlobalCompilerVisitor)
837 do
838 var cc = v.global_analysis.compiled_classes[self.global]
839 var ctab = cc.class_table
840 var clen = ctab.length
841 if v.global_analysis.max_class_table_length > ctab.length then
842 clen = v.global_analysis.max_class_table_length
843 end
844
845 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
846 v.indent
847 for e in ctab do
848 if e == null then
849 v.add_instr("\{0} /* Class Hole :( */,")
850 else
851 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
852 end
853 end
854 if clen > ctab.length then
855 v.add_instr("\{0},"*(clen-ctab.length))
856 end
857 v.unindent
858 v.add_instr("};")
859 var itab = cc.instance_table
860 for e in itab do
861 if e == null then
862 v.add_instr("/* Instance Hole :( */")
863 else
864 v.add_instr(e.compile_to_c(v, self))
865 end
866 end
867
868 var pi = primitive_info
869 if pi == null then
870 v.cfc = new CFunctionContext(v)
871 v.nmc = new NitMethodContext(null)
872 var s = "val_t NEW_{name}(void)"
873 v.add_instr(s + " \{")
874 v.indent
875 var ctx_old = v.ctx
876 v.ctx = new CContext
877
878 var self_var = new ParamVariable(once ("self".to_symbol), null)
879 var self_var_cname = v.cfc.register_variable(self_var)
880 v.nmc.method_params = [self_var]
881
882 v.add_instr("obj_t obj;")
883 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
884 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
885 v.add_assignment(self_var_cname, "OBJ2VAL(obj)")
886
887 for g in global_properties do
888 var p = self[g]
889 var t = p.signature.return_type
890 if p isa MMAttribute and t != null then
891 # FIXME: Not compatible with sep compilation
892 assert p isa MMSrcAttribute
893 var np = p.node
894 var ne = np.n_expr
895 if ne != null then
896 var e = ne.compile_expr(v)
897 v.add_instr("{p.global.attr_access}(obj) = {e};")
898 end
899 end
900 end
901 v.add_instr("return OBJ2VAL(obj);")
902 v.cfc.generate_var_decls
903 ctx_old.append(v.ctx)
904 v.ctx = ctx_old
905 v.unindent
906 v.add_instr("}")
907
908 # Compile CHECKNAME
909 var s = "void CHECKNEW_{name}(val_t self, char *from)"
910 v.add_instr(s + " \{")
911 v.indent
912 var ctx_old = v.ctx
913 v.ctx = new CContext
914 for g in global_properties do
915 var p = self[g]
916 var t = p.signature.return_type
917 if p isa MMAttribute and t != null and not t.is_nullable then
918 v.add_instr("if ({p.global.attr_access}(self) == NIT_NULL) \{ fprintf(stderr, \"Uninitialized attribute %s at %s.\\n\", \"{p.full_name}\", from); nit_exit(1); \}")
919 end
920 end
921 ctx_old.append(v.ctx)
922 v.ctx = ctx_old
923 v.unindent
924 v.add_instr("}")
925
926 var init_table_size = cshe.greaters.length + 1
927 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
928
929 for g in global_properties do
930 var p = self[g]
931 # FIXME skip invisible constructors
932 if not p.global.is_init_for(self) then continue
933 var params = new Array[String]
934 var args = ["self"]
935 for i in [0..p.signature.arity[ do
936 params.add("val_t p{i}")
937 args.add("p{i}")
938 end
939 args.add("init_table")
940 var s = "val_t NEW_{self}_{p.global.intro.cname}({params.join(", ")}) \{"
941 v.add_instr(s)
942 v.indent
943 v.add_instr(init_table_decl)
944 v.add_instr("val_t self = NEW_{name}();")
945 v.add_instr("{p.cname}({args.join(", ")});")
946 v.add_instr("CHECKNEW_{name}(self, \"{p.full_name} for {self}\");")
947 v.add_instr("return self;")
948 v.unindent
949 v.add_instr("}")
950 end
951 else if not pi.tagged then
952 var t = pi.cname
953 var tbox = "struct TBOX_{name}"
954 v.add_instr("val_t BOX_{name}({t} val) \{")
955 v.indent
956 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
957 v.add_instr("box->vft = VFT_{name};")
958 v.add_instr("box->val = val;")
959 v.add_instr("return OBJ2VAL(box);")
960 v.unindent
961 v.add_instr("}")
962 end
963 end
964 end
965