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