Merge branch 'alexandre/at-various-fixes' into wip
[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 table_computation
21 private import compiling_icode
22
23 redef class Program
24 # Compile module and class tables
25 fun compile_tables_to_c(v: CompilerVisitor)
26 do
27 for m in main_module.mhe.greaters_and_self do
28 m.compile_local_table_to_c(v)
29 end
30
31 with_each_live_local_classes !action(c) do
32 if c.global.is_abstract or c.global.is_interface then continue
33 c.compile_tables_to_c(v)
34 end
35
36 var s = new Buffer.from("classtable_t TAG2VFT[4] = \{NULL")
37 for t in ["Int","Char","Bool"] do
38 if main_module.has_global_class_named(t.to_symbol) then
39 s.append(", (const classtable_t)VFT_{t}")
40 else
41 s.append(", NULL")
42 end
43 end
44 s.append("};")
45 v.add_instr(s.to_s)
46 end
47
48 # Compile main part (for _table.c)
49 fun compile_main_part(v: CompilerVisitor)
50 do
51 v.add_instr("int main(int argc, char **argv) \{")
52 v.indent
53 v.add_instr("prepare_signals();")
54 v.add_instr("glob_argc = argc; glob_argv = argv;")
55 if v.program.main_method == null then
56 print("No main")
57 else
58 v.add_instr("G_sys = NEW_Sys();")
59 v.add_instr("register_static_object(&G_sys);")
60 v.add_instr("{v.program.main_method.cname}(G_sys);")
61 end
62 v.add_instr("return 0;")
63 v.unindent
64 v.add_instr("}")
65 end
66 end
67
68 redef class MMModule
69 # Declare class table (for _sep.h or _glob.h)
70 fun declare_class_tables_to_c(v: CompilerVisitor)
71 do
72 for c in local_classes do
73 if c.global.mmmodule == self then
74 c.declare_tables_to_c(v)
75 end
76 end
77 end
78
79 # Compile sep files
80 fun compile_mod_to_c(v: CompilerVisitor)
81 do
82 v.add_decl("extern const char *LOCATE_{name};")
83 if not v.program.tc.use_SFT_optimization then
84 v.add_decl("extern const int SFT_{name}[];")
85 end
86 var i = 0
87 for e in local_table do
88 var value: String
89 if v.program.tc.use_SFT_optimization then
90 value = "{e.value(v.program)}"
91 else
92 value = "SFT_{name}[{i}]"
93 i = i + 1
94 end
95 e.compile_macros(v, value)
96 end
97 for c in local_classes do
98 if not c isa MMConcreteClass then continue
99 for pg in c.global_properties do
100 var p = c[pg]
101 if p.local_class == c and p isa MMMethod then
102 p.compile_property_to_c(v)
103 end
104 if pg.is_init_for(c) then
105 # Declare constructors
106 var params = new Array[String]
107 for j in [0..p.signature.arity[ do
108 params.add("val_t p{j}")
109 end
110 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
111 end
112 end
113 end
114 end
115
116 # Compile module file for the current module
117 fun compile_local_table_to_c(v: CompilerVisitor)
118 do
119 v.add_instr("const char *LOCATE_{name} = \"{location.file.filename}\";")
120
121 if v.program.tc.use_SFT_optimization or local_table.is_empty then
122 return
123 end
124
125 v.add_instr("const int SFT_{name}[{local_table.length}] = \{")
126 v.indent
127 for e in local_table do
128 v.add_instr(e.value(v.program) + ",")
129 end
130 v.unindent
131 v.add_instr("\};")
132 end
133 end
134
135 ###############################################################################
136
137 redef class AbsTableElt
138 # Compile the macro needed to use the element and other related elements
139 fun compile_macros(v: CompilerVisitor, value: String) is abstract
140 end
141
142 redef class TableElt
143 # Return the value of the element for a given class
144 fun compile_to_c(v: CompilerVisitor, c: MMLocalClass): String is abstract
145 end
146
147 redef class ModuleTableElt
148 # Return the value of the element once the global analisys is performed
149 fun value(prog: Program): String is abstract
150 end
151
152 redef class ModuleTableEltGroup
153 redef fun value(prog) do return "{prog.table_information.color(elements.first)} /* Group of ? */"
154 redef fun compile_macros(v, value)
155 do
156 var i = 0
157 for e in elements do
158 e.compile_macros(v, "{value} + {i}")
159 i += 1
160 end
161 end
162 end
163
164 redef class TableEltMeth
165 redef fun compile_macros(v, value)
166 do
167 var pg = property.global
168 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
169 end
170
171 redef fun compile_to_c(v, c)
172 do
173 var p = c[property.global]
174 return p.cname
175 end
176 end
177
178 redef class TableEltSuper
179 redef fun compile_macros(v, value)
180 do
181 var p = property
182 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
183 end
184
185 redef fun compile_to_c(v, c)
186 do
187 var pc = property.local_class
188 var g = property.global
189 var lin = c.che.linear_extension
190 var found = false
191 for s in lin do
192 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
193 if s == pc then
194 found = true
195 else if found and c.che < s then
196 if s.has_global_property(g) then
197 #print "found {s.module}::{s}::{p}"
198 return s[g].cname
199 end
200 end
201 end
202 abort
203 end
204 end
205
206 redef class TableEltAttr
207 redef fun compile_macros(v, value)
208 do
209 var pg = property.global
210 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
211 end
212
213 redef fun compile_to_c(v, c)
214 do
215 var prog = v.program
216 var p = c[property.global]
217 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
218 end
219 end
220
221 redef class AbsTableEltClass
222 # The C macro name refering the value
223 fun symbol: String is abstract
224
225 redef fun compile_macros(v, value)
226 do
227 v.add_decl("#define {symbol} ({value})")
228 end
229 end
230
231 redef class TableEltClassId
232 redef fun symbol do return local_class.global.id_id
233
234 redef fun value(prog)
235 do
236 return "{prog.compiled_classes[local_class.global].id} /* Id of {local_class} */"
237 end
238 end
239
240 redef class TableEltClassInitTable
241 redef fun symbol do return local_class.global.init_table_pos_id
242
243 redef fun compile_to_c(v, c)
244 do
245 var prog = v.program
246 var cc = prog.compiled_classes[local_class.global]
247 var linext = c.cshe.reverse_linear_extension
248 var i = 0
249 while linext[i].global != local_class.global do
250 i += 1
251 end
252 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
253 end
254 end
255
256 redef class TableEltClassColor
257 redef fun symbol do return local_class.global.color_id
258
259 redef fun value(prog)
260 do
261 return "{prog.table_information.color(self)} /* Color of {local_class} */"
262 end
263
264 redef fun compile_to_c(v, c)
265 do
266 var prog = v.program
267 var cc = prog.compiled_classes[local_class.global]
268 return "{cc.id} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
269 end
270 end
271
272 redef class TableEltComposite
273 redef fun compile_to_c(v, c) do abort
274 end
275
276 redef class TableEltClassSelfId
277 redef fun compile_to_c(v, c)
278 do
279 var prog = v.program
280 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
281 end
282 end
283
284 redef class TableEltClassSelfName
285 redef fun compile_to_c(v, c)
286 do
287 var prog = v.program
288 return "\"{c.global.name}\" /* {prog.table_information.color(self)}: Class Name */"
289 end
290 end
291
292 redef class TableEltClassObjectSize
293 redef fun compile_to_c(v, c)
294 do
295 var nb = 0
296 var p = v.program
297 if c.name == "NativeArray".to_symbol then
298 nb = -1
299 else
300 var cc = p.compiled_classes[c.global]
301 var itab = cc.instance_table
302 for e in itab do
303 nb += 1
304 end
305 end
306 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
307 end
308 end
309
310 redef class TableEltObjectId
311 redef fun compile_to_c(v, c)
312 do
313 var p = v.program
314 return "/* {p.table_information.color(self)}: Object_id */"
315 end
316 end
317
318 redef class TableEltVftPointer
319 redef fun compile_to_c(v, c)
320 do
321 var prog = v.program
322 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
323 end
324 end
325
326 ###############################################################################
327
328 redef class MMLocalClass
329 # Declaration and macros related to the class table
330 fun declare_tables_to_c(v: CompilerVisitor)
331 do
332 v.add_decl("")
333 var pi = primitive_info
334 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
335 if pi != null and not pi.tagged then
336 var t = pi.cname
337 var tbox = "struct TBOX_{name}"
338 v.add_decl("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
339 v.add_decl("val_t BOX_{name}({t} val);")
340 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
341 end
342 end
343
344 # Compilation of table and new (or box)
345 fun compile_tables_to_c(v: CompilerVisitor)
346 do
347 var cc = v.program.compiled_classes[self.global]
348 var ctab = cc.class_table
349 var clen = ctab.length
350 if v.program.table_information.max_class_table_length > ctab.length then
351 clen = v.program.table_information.max_class_table_length
352 end
353
354 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
355 v.indent
356 for e in ctab do
357 if e == null then
358 v.add_instr("\{0} /* Class Hole :( */,")
359 else
360 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
361 end
362 end
363 if clen > ctab.length then
364 v.add_instr("\{0},"*(clen-ctab.length))
365 end
366 v.unindent
367 v.add_instr("};")
368 var itab = cc.instance_table
369 for e in itab do
370 if e == null then
371 v.add_instr("/* Instance Hole :( */")
372 else
373 v.add_instr(e.compile_to_c(v, self))
374 end
375 end
376
377 var pi = primitive_info
378 if name == "NativeArray".to_symbol then
379 v.add_instr("val_t NEW_NativeArray(size_t length, size_t size) \{")
380 v.indent
381 v.add_instr("Nit_NativeArray array;")
382 v.add_instr("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
383 v.add_instr("array->vft = (classtable_elt_t*)VFT_{name};")
384 v.add_instr("array->object_id = object_id_counter;")
385 v.add_instr("object_id_counter = object_id_counter + 1;")
386 v.add_instr("array->size = length;")
387 v.add_instr("return OBJ2VAL(array);")
388 v.unindent
389 v.add_instr("}")
390 else if pi == null then
391 do
392 # Generate INIT_ATTRIBUTES routine
393 var cname = "INIT_ATTRIBUTES__{name}"
394 var args = init_var_iroutine.compile_signature_to_c(v, cname, "init var of {name}", null, null)
395 var decl_writer_old = v.decl_writer
396 v.decl_writer = v.writer.sub
397 init_var_iroutine.compile_to_c(v, cname, args)
398 v.decl_writer = decl_writer_old
399 v.unindent
400 v.add_instr("}")
401 end
402 do
403 # Generate NEW routine
404 v.add_decl("val_t NEW_{name}(void);")
405 v.add_instr("val_t NEW_{name}(void)")
406 v.add_instr("\{")
407 v.indent
408 v.add_instr("obj_t obj;")
409 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
410 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
411 v.add_instr("obj[1].object_id = object_id_counter;")
412 v.add_instr("object_id_counter = object_id_counter + 1;")
413 v.add_instr("return OBJ2VAL(obj);")
414 v.unindent
415 v.add_instr("}")
416 end
417 do
418 # Compile CHECKNAME
419 var cname = "CHECKNEW_{name}"
420 var args = checknew_iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
421 var decl_writer_old = v.decl_writer
422 v.decl_writer = v.writer.sub
423 checknew_iroutine.compile_to_c(v, cname, args)
424 v.decl_writer = decl_writer_old
425 v.unindent
426 v.add_instr("}")
427 end
428
429 var init_table_size = cshe.greaters.length + 1
430 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
431
432 for g in global_properties do
433 var p = self[g]
434 # FIXME skip invisible constructors
435 if not p.global.is_init_for(self) then continue
436 assert p isa MMMethod
437
438 var cname = "NEW_{self}_{p.global.intro.cname}"
439 var new_args = new_instance_iroutine[p].compile_signature_to_c(v, cname, "new {self} {p.full_name}", null, null)
440 var decl_writer_old = v.decl_writer
441 v.decl_writer = v.writer.sub
442 v.add_instr(init_table_decl)
443 var e = new_instance_iroutine[p].compile_to_c(v, cname, new_args).as(not null)
444 v.add_instr("return {e};")
445 v.decl_writer = decl_writer_old
446 v.unindent
447 v.add_instr("}")
448 end
449 else if not pi.tagged then
450 var t = pi.cname
451 var tbox = "struct TBOX_{name}"
452 v.add_instr("val_t BOX_{name}({t} val) \{")
453 v.indent
454 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
455 v.add_instr("box->vft = VFT_{name};")
456 v.add_instr("box->val = val;")
457 v.add_instr("box->object_id = object_id_counter;")
458 v.add_instr("object_id_counter = object_id_counter + 1;")
459 v.add_instr("return OBJ2VAL(box);")
460 v.unindent
461 v.add_instr("}")
462 end
463 end
464 end
465
466 redef class MMMethod
467 fun compile_property_to_c(v: CompilerVisitor)
468 do
469 var ir = iroutine
470 assert ir != null
471
472 var more_params: nullable String = null
473 if global.is_init then more_params = "int* init_table"
474 var args = ir.compile_signature_to_c(v, cname, full_name, null, more_params)
475 var writer_old = v.writer
476 v.writer = v.writer.sub
477 var decl_writer_old = v.decl_writer
478 v.decl_writer = v.writer.sub
479
480 var itpos: nullable String = null
481 if global.is_init then
482 itpos = "itpos{v.new_number}"
483 v.add_decl("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
484 v.add_instr("if (init_table[{itpos}]) return;")
485 end
486
487 var s = ir.compile_to_c(v, cname, args)
488
489 if itpos != null then
490 v.add_instr("init_table[{itpos}] = 1;")
491 end
492 if s == null then
493 v.add_instr("return;")
494 else
495 v.add_instr("return {s};")
496 end
497 v.unindent
498 v.add_instr("}")
499
500 v.writer = writer_old
501 v.decl_writer = decl_writer_old
502 end
503 end
504