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