da63476dc1513d88b310de33d6821afc865fedf8
[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}\";")
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 TableEltClassObjectSize
285 redef fun compile_to_c(v, c)
286 do
287 var nb = 0
288 var p = v.program
289 if c.name == "NativeArray".to_symbol then
290 nb = -1
291 else
292 var cc = p.compiled_classes[c.global]
293 var itab = cc.instance_table
294 for e in itab do
295 nb += 1
296 end
297 end
298 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
299 end
300 end
301
302 redef class TableEltObjectId
303 redef fun compile_to_c(v, c)
304 do
305 var p = v.program
306 return "/* {p.table_information.color(self)}: Object_id */"
307 end
308 end
309
310 redef class TableEltVftPointer
311 redef fun compile_to_c(v, c)
312 do
313 var prog = v.program
314 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
315 end
316 end
317
318 ###############################################################################
319
320 redef class MMLocalClass
321 # Declaration and macros related to the class table
322 fun declare_tables_to_c(v: CompilerVisitor)
323 do
324 v.add_decl("")
325 var pi = primitive_info
326 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
327 if pi != null and not pi.tagged then
328 var t = pi.cname
329 var tbox = "struct TBOX_{name}"
330 v.add_decl("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
331 v.add_decl("val_t BOX_{name}({t} val);")
332 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
333 end
334 end
335
336 # Compilation of table and new (or box)
337 fun compile_tables_to_c(v: CompilerVisitor)
338 do
339 var cc = v.program.compiled_classes[self.global]
340 var ctab = cc.class_table
341 var clen = ctab.length
342 if v.program.table_information.max_class_table_length > ctab.length then
343 clen = v.program.table_information.max_class_table_length
344 end
345
346 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
347 v.indent
348 for e in ctab do
349 if e == null then
350 v.add_instr("\{0} /* Class Hole :( */,")
351 else
352 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
353 end
354 end
355 if clen > ctab.length then
356 v.add_instr("\{0},"*(clen-ctab.length))
357 end
358 v.unindent
359 v.add_instr("};")
360 var itab = cc.instance_table
361 for e in itab do
362 if e == null then
363 v.add_instr("/* Instance Hole :( */")
364 else
365 v.add_instr(e.compile_to_c(v, self))
366 end
367 end
368
369 var pi = primitive_info
370 if name == "NativeArray".to_symbol then
371 v.add_instr("val_t NEW_NativeArray(size_t length, size_t size) \{")
372 v.indent
373 v.add_instr("Nit_NativeArray array;")
374 v.add_instr("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
375 v.add_instr("array->vft = (classtable_elt_t*)VFT_{name};")
376 v.add_instr("array->object_id = object_id_counter;")
377 v.add_instr("object_id_counter = object_id_counter + 1;")
378 v.add_instr("array->size = length;")
379 v.add_instr("return OBJ2VAL(array);")
380 v.unindent
381 v.add_instr("}")
382 else if pi == null then
383 do
384 # Generate INIT_ATTRIBUTES routine
385 var cname = "INIT_ATTRIBUTES__{name}"
386 var args = init_var_iroutine.compile_signature_to_c(v, cname, "init var of {name}", null, null)
387 var decl_writer_old = v.decl_writer
388 v.decl_writer = v.writer.sub
389 init_var_iroutine.compile_to_c(v, cname, args)
390 v.decl_writer = decl_writer_old
391 v.unindent
392 v.add_instr("}")
393 end
394 do
395 # Generate NEW routine
396 v.add_decl("val_t NEW_{name}(void);")
397 v.add_instr("val_t NEW_{name}(void)")
398 v.add_instr("\{")
399 v.indent
400 v.add_instr("obj_t obj;")
401 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
402 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
403 v.add_instr("obj[1].object_id = object_id_counter;")
404 v.add_instr("object_id_counter = object_id_counter + 1;")
405 v.add_instr("return OBJ2VAL(obj);")
406 v.unindent
407 v.add_instr("}")
408 end
409 do
410 # Compile CHECKNAME
411 var cname = "CHECKNEW_{name}"
412 var args = checknew_iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
413 var decl_writer_old = v.decl_writer
414 v.decl_writer = v.writer.sub
415 checknew_iroutine.compile_to_c(v, cname, args)
416 v.decl_writer = decl_writer_old
417 v.unindent
418 v.add_instr("}")
419 end
420
421 var init_table_size = cshe.greaters.length + 1
422 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
423
424 for g in global_properties do
425 var p = self[g]
426 # FIXME skip invisible constructors
427 if not p.global.is_init_for(self) then continue
428 assert p isa MMMethod
429
430 var cname = "NEW_{self}_{p.global.intro.cname}"
431 var new_args = new_instance_iroutine[p].compile_signature_to_c(v, cname, "new {self} {p.full_name}", null, null)
432 var decl_writer_old = v.decl_writer
433 v.decl_writer = v.writer.sub
434 v.add_instr(init_table_decl)
435 var e = new_instance_iroutine[p].compile_to_c(v, cname, new_args).as(not null)
436 v.add_instr("return {e};")
437 v.decl_writer = decl_writer_old
438 v.unindent
439 v.add_instr("}")
440 end
441 else if not pi.tagged then
442 var t = pi.cname
443 var tbox = "struct TBOX_{name}"
444 v.add_instr("val_t BOX_{name}({t} val) \{")
445 v.indent
446 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
447 v.add_instr("box->vft = VFT_{name};")
448 v.add_instr("box->val = val;")
449 v.add_instr("box->object_id = object_id_counter;")
450 v.add_instr("object_id_counter = object_id_counter + 1;")
451 v.add_instr("return OBJ2VAL(box);")
452 v.unindent
453 v.add_instr("}")
454 end
455 end
456 end
457
458 redef class MMMethod
459 fun compile_property_to_c(v: CompilerVisitor)
460 do
461 var ir = iroutine
462 assert ir != null
463
464 var more_params: nullable String = null
465 if global.is_init then more_params = "int* init_table"
466 var args = ir.compile_signature_to_c(v, cname, full_name, null, more_params)
467 var writer_old = v.writer
468 v.writer = v.writer.sub
469 var decl_writer_old = v.decl_writer
470 v.decl_writer = v.writer.sub
471
472 var itpos: nullable String = null
473 if global.is_init then
474 itpos = "itpos{v.new_number}"
475 v.add_decl("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
476 v.add_instr("if (init_table[{itpos}]) return;")
477 end
478
479 var s = ir.compile_to_c(v, cname, args)
480
481 if itpos != null then
482 v.add_instr("init_table[{itpos}] = 1;")
483 end
484 if s == null then
485 v.add_instr("return;")
486 else
487 v.add_instr("return {s};")
488 end
489 v.unindent
490 v.add_instr("}")
491
492 v.writer = writer_old
493 v.decl_writer = decl_writer_old
494 end
495 end
496