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