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