pep8analysis: fix format and encoding of some sample/test programs
[nit.git] / src / global_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 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 # Global compilation of a Nit program
18 #
19 # Techniques used are:
20 # * heterogeneous generics
21 # * customization
22 # * switch dispatch
23 # * inlining
24 module global_compiler
25
26 import abstract_compiler
27 import rapid_type_analysis
28
29 redef class ToolContext
30 # option --global
31 var opt_global = new OptionBool("Use global compilation", "--global")
32
33 var global_compiler_phase = new GlobalCompilerPhase(self, null)
34
35 redef init do
36 super
37 option_context.add_option(opt_global)
38 end
39 end
40
41 class GlobalCompilerPhase
42 super Phase
43 redef fun process_mainmodule(mainmodule, given_mmodules) do
44 if not toolcontext.opt_global.value then return
45
46 var modelbuilder = toolcontext.modelbuilder
47 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
48 modelbuilder.run_global_compiler(mainmodule, analysis)
49 end
50 end
51
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
57 do
58 var time0 = get_time
59 self.toolcontext.info("*** GENERATING C ***", 1)
60
61 var compiler = new GlobalCompiler(mainmodule, self, runtime_type_analysis)
62 compiler.compile_header
63
64 for t in runtime_type_analysis.live_types do
65 compiler.declare_runtimeclass(t)
66 end
67
68 compiler.compile_class_names
69
70 # Init instance code (allocate and init-arguments)
71 for t in runtime_type_analysis.live_types do
72 if t.ctype == "val*" then
73 compiler.generate_init_instance(t)
74 else
75 compiler.generate_box_instance(t)
76 end
77 end
78
79 # The main function of the C
80 compiler.compile_main_function
81
82 # Compile until all runtime_functions are visited
83 while not compiler.todos.is_empty do
84 var m = compiler.todos.shift
85 self.toolcontext.info("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
86 m.compile_to_c(compiler)
87 end
88 self.toolcontext.info("Total methods to compile to C: {compiler.seen.length}", 2)
89
90 compiler.display_stats
91
92 var time1 = get_time
93 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
94 write_and_make(compiler)
95 end
96 end
97
98 # Compiler that use global compilation and perform hard optimisations like:
99 # * customization
100 # * switch dispatch
101 # * inlining
102 class GlobalCompiler
103 super AbstractCompiler
104
105 redef type VISITOR: GlobalCompilerVisitor
106
107 # The result of the RTA (used to know live types and methods)
108 var runtime_type_analysis: RapidTypeAnalysis
109
110 init(mainmodule: MModule, modelbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis)
111 do
112 super(mainmodule, modelbuilder)
113 var file = new_file("{mainmodule.name}.nitgg")
114 self.header = new CodeWriter(file)
115 self.runtime_type_analysis = runtime_type_analysis
116 self.live_primitive_types = new Array[MClassType]
117 for t in runtime_type_analysis.live_types do
118 if t.ctype != "val*" then
119 self.live_primitive_types.add(t)
120 end
121 end
122 end
123
124 # Compile class names (for the class_name and output_class_name methods)
125 protected fun compile_class_names do
126 var v = new_visitor
127 self.header.add_decl("extern const char const * class_names[];")
128 v.add("const char const * class_names[] = \{")
129 for t in self.runtime_type_analysis.live_types do
130 v.add("\"{t}\", /* {self.classid(t)} */")
131 end
132 v.add("\};")
133 end
134
135 # Return the C symbol associated to a live type runtime
136 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
137 fun classid(mtype: MClassType): String
138 do
139 if self.classids.has_key(mtype) then
140 return self.classids[mtype]
141 end
142 print "No classid for {mtype}"
143 abort
144 end
145
146 # Cache for classid
147 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
148
149 # Declaration of structures the live Nit types
150 # Each live type is generated as an independent C `struct` type.
151 # They only share a common first field `classid` used to implement the polymorphism.
152 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
153 redef fun compile_header_structs do
154 self.header.add_decl("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
155 end
156
157 # Subset of runtime_type_analysis.live_types that contains only primitive types
158 # Used to implement the equal test
159 var live_primitive_types: Array[MClassType]
160
161 # Add a new todo task
162 fun todo(m: AbstractRuntimeFunction)
163 do
164 if seen.has(m) then return
165 todos.add(m)
166 seen.add(m)
167 end
168
169 # runtime_functions that need to be compiled
170 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
171
172 # runtime_functions already seen (todo or done)
173 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
174
175 # Declare C structures and identifiers for a runtime class
176 fun declare_runtimeclass(mtype: MClassType)
177 do
178 var v = self.header
179 assert self.runtime_type_analysis.live_types.has(mtype)
180 v.add_decl("/* runtime class {mtype} */")
181 var idnum = classids.length
182 var idname = "ID_" + mtype.c_name
183 self.classids[mtype] = idname
184 v.add_decl("#define {idname} {idnum} /* {mtype} */")
185
186 v.add_decl("struct {mtype.c_name} \{")
187 v.add_decl("int classid; /* must be {idname} */")
188
189 if mtype.mclass.name == "NativeArray" then
190 # NativeArrays are just a instance header followed by an array of values
191 v.add_decl("int length;")
192 v.add_decl("{mtype.arguments.first.ctype} values[1];")
193 end
194
195 if mtype.ctype != "val*" then
196 # Is the Nit type is native then the struct is a box with two fields:
197 # * the `classid` to be polymorph
198 # * the `value` that contains the native value.
199 v.add_decl("{mtype.ctype} value;")
200 end
201
202 # Collect all attributes and associate them a field in the structure.
203 # Note: we do not try to optimize the order and helps CC to optimize the client code.
204 for cd in mtype.collect_mclassdefs(self.mainmodule) do
205 for p in cd.intro_mproperties do
206 if not p isa MAttribute then continue
207 var t = p.intro.static_mtype.as(not null)
208 t = t.anchor_to(self.mainmodule, mtype)
209 v.add_decl("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
210 end
211 end
212 v.add_decl("\};")
213 end
214
215 # Generate the init-instance of a live type (allocate + init-instance)
216 fun generate_init_instance(mtype: MClassType)
217 do
218 assert self.runtime_type_analysis.live_types.has(mtype)
219 assert mtype.ctype == "val*"
220 var v = self.new_visitor
221
222 var is_native_array = mtype.mclass.name == "NativeArray"
223
224 var sig
225 if is_native_array then
226 sig = "int length"
227 else
228 sig = "void"
229 end
230
231 self.header.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig});")
232 v.add_decl("/* allocate {mtype} */")
233 v.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
234 var res = v.new_var(mtype)
235 res.is_exact = true
236 if is_native_array then
237 var mtype_elt = mtype.arguments.first
238 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
239 v.add("((struct {mtype.c_name}*){res})->length = length;")
240 else
241 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
242 end
243 v.add("{res}->classid = {self.classid(mtype)};")
244
245 self.generate_init_attr(v, res, mtype)
246 v.add("return {res};")
247 v.add("\}")
248 end
249
250 fun generate_box_instance(mtype: MClassType)
251 do
252 assert self.runtime_type_analysis.live_types.has(mtype)
253 assert mtype.ctype != "val*"
254 var v = self.new_visitor
255
256 self.header.add_decl("val* BOX_{mtype.c_name}({mtype.ctype});")
257 v.add_decl("/* allocate {mtype} */")
258 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
259 v.add("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
260 v.add("res->classid = {self.classid(mtype)};")
261 v.add("res->value = value;")
262 v.add("return (val*)res;")
263 v.add("\}")
264 end
265
266 redef fun new_visitor do return new GlobalCompilerVisitor(self)
267
268 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
269
270 redef fun compile_nitni_structs
271 do
272 self.header.add_decl("struct nitni_instance \{ val *value; \};")
273 end
274 end
275
276 # A visitor on the AST of property definition that generate the C code.
277 # Because of inlining, a visitor can visit more than one property.
278 class GlobalCompilerVisitor
279 super AbstractCompilerVisitor
280
281 redef type COMPILER: GlobalCompiler
282
283 redef fun autobox(value, mtype)
284 do
285 if value.mtype == mtype then
286 return value
287 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
288 return value
289 else if value.mtype.ctype == "val*" then
290 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
291 else if mtype.ctype == "val*" then
292 var valtype = value.mtype.as(MClassType)
293 var res = self.new_var(mtype)
294 if not compiler.runtime_type_analysis.live_types.has(valtype) then
295 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
296 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); show_backtrace(1);")
297 return res
298 end
299 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
300 return res
301 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
302 return value
303 else
304 # Bad things will appen!
305 var res = self.new_var(mtype)
306 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
307 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); show_backtrace(1);")
308 return res
309 end
310 end
311
312 # The runtime types that are acceptable for a given receiver.
313 fun collect_types(recv: RuntimeVariable): Array[MClassType]
314 do
315 var mtype = recv.mcasttype
316 if recv.is_exact then
317 assert mtype isa MClassType
318 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
319 var types = [mtype]
320 return types
321 end
322 var cache = self.compiler.collect_types_cache
323 if cache.has_key(mtype) then
324 return cache[mtype]
325 end
326 var types = new Array[MClassType]
327 var mainmodule = self.compiler.mainmodule
328 for t in self.compiler.runtime_type_analysis.live_types do
329 if not t.is_subtype(mainmodule, null, mtype) then continue
330 types.add(t)
331 end
332 cache[mtype] = types
333 return types
334 end
335
336 redef fun native_array_def(pname, ret_type, arguments)
337 do
338 var elttype = arguments.first.mtype
339 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
340 if pname == "[]" then
341 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
342 return
343 else if pname == "[]=" then
344 self.add("{recv}[{arguments[1]}]={arguments[2]};")
345 return
346 else if pname == "length" then
347 self.ret(self.new_expr("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type.as(not null)))
348 return
349 else if pname == "copy_to" then
350 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
351 self.add("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
352 return
353 end
354 end
355
356 redef fun calloc_array(ret_type, arguments)
357 do
358 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
359 end
360
361 redef fun send(m, args)
362 do
363 var types = self.collect_types(args.first)
364
365 var res: nullable RuntimeVariable
366 var ret = m.intro.msignature.return_mtype
367 if m.is_new then
368 ret = args.first.mtype
369 res = self.new_var(ret)
370 else if ret == null then
371 res = null
372 else
373 ret = self.resolve_for(ret, args.first)
374 res = self.new_var(ret)
375 end
376
377 self.add("/* send {m} on {args.first.inspect} */")
378 if args.first.mtype.ctype != "val*" then
379 var mclasstype = args.first.mtype.as(MClassType)
380 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
381 self.add("/* skip, no method {m} */")
382 return res
383 end
384 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
385 var res2 = self.call(propdef, mclasstype, args)
386 if res != null then self.assign(res, res2.as(not null))
387 return res
388 end
389 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or m.name == "==" or m.name == "!="
390 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
391 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
392 self.add("if ({args.first} == NULL) \{ /* Special null case */")
393 if m.name == "==" then
394 assert res != null
395 if args[1].mcasttype isa MNullableType then
396 self.add("{res} = ({args[1]} == NULL);")
397 else if args[1].mcasttype isa MNullType then
398 self.add("{res} = 1; /* is null */")
399 else
400 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
401 end
402 else if m.name == "!=" then
403 assert res != null
404 if args[1].mcasttype isa MNullableType then
405 self.add("{res} = ({args[1]} != NULL);")
406 else if args[1].mcasttype isa MNullType then
407 self.add("{res} = 0; /* is null */")
408 else
409 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
410 end
411 else
412 self.add_abort("Receiver is null")
413 end
414 self.add "\} else"
415 end
416 if types.is_empty then
417 self.add("\{")
418 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
419 self.bugtype(args.first)
420 self.add("\}")
421 return res
422 end
423
424 self.add("switch({args.first}->classid) \{")
425 var last = types.last
426 var defaultpropdef: nullable MMethodDef = null
427 for t in types do
428 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
429 if propdef.mclassdef.mclass.name == "Object" and t.ctype == "val*" then
430 defaultpropdef = propdef
431 continue
432 end
433 if not self.compiler.hardening and t == last and defaultpropdef == null then
434 self.add("default: /* test {t} */")
435 else
436 self.add("case {self.compiler.classid(t)}: /* test {t} */")
437 end
438 var res2 = self.call(propdef, t, args)
439 if res != null then self.assign(res, res2.as(not null))
440 self.add "break;"
441 end
442 if defaultpropdef != null then
443 self.add("default: /* default is Object */")
444 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
445 if res != null then self.assign(res, res2.as(not null))
446 else if self.compiler.hardening then
447 self.add("default: /* bug */")
448 self.bugtype(args.first)
449 end
450 self.add("\}")
451 return res
452 end
453
454 fun check_valid_reciever(recvtype: MClassType)
455 do
456 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
457 print "{recvtype} is not a live type"
458 abort
459 end
460
461 # Subpart of old call function
462 #
463 # Checks if the type of the receiver is valid and corrects it if necessary
464 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
465 do
466 check_valid_reciever(recvtype)
467 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
468 if m.mclassdef.mclass.name == "Object" and recvtype.ctype == "val*" then
469 recvtype = m.mclassdef.bound_mtype
470 end
471 return recvtype
472 end
473
474 # Subpart of old call function
475 # Gets the receiver boxed and casted if necessary
476 private fun get_recv(recvtype: MClassType, args: Array[RuntimeVariable]): RuntimeVariable
477 do
478 return self.autoadapt(self.autobox(args.first, recvtype), recvtype)
479 end
480
481 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
482 private fun finalize_call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
483 do
484 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
485
486 var rm = new CustomizedRuntimeFunction(m, recvtype)
487 return rm.call(self, args)
488 end
489
490 redef fun call(m, recvtype, args)
491 do
492 var recv_type = get_recvtype(m, recvtype, args)
493 var recv = get_recv(recv_type, args)
494 var new_args = args.to_a
495 self.varargize(m, m.msignature.as(not null), new_args)
496 new_args.first = recv
497 return finalize_call(m, recv_type, new_args)
498 end
499
500 # Does a call without encapsulating varargs into an array
501 # Avoids multiple encapsulation when calling a super in a variadic function
502 fun call_without_varargize(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
503 do
504 var recv_type = get_recvtype(m, recvtype, args)
505 var recv = get_recv(recv_type, args)
506 var new_args = args.to_a
507 new_args.first = recv
508 return finalize_call(m, recv_type, new_args)
509 end
510
511 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
512 do
513 var types = self.collect_types(args.first)
514
515 var res: nullable RuntimeVariable
516 var ret = m.mproperty.intro.msignature.return_mtype
517 if ret == null then
518 res = null
519 else
520 ret = self.resolve_for(ret, args.first)
521 res = self.new_var(ret)
522 end
523
524 self.add("/* super {m} on {args.first.inspect} */")
525 if args.first.mtype.ctype != "val*" then
526 var mclasstype = args.first.mtype.as(MClassType)
527 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
528 self.add("/* skip, no method {m} */")
529 return res
530 end
531 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
532 var res2 = self.call_without_varargize(propdef, mclasstype, args)
533 if res != null then self.assign(res, res2.as(not null))
534 return res
535 end
536
537 if types.is_empty then
538 self.add("\{")
539 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
540 self.bugtype(args.first)
541 self.add("\}")
542 return res
543 end
544
545 self.add("switch({args.first}->classid) \{")
546 var last = types.last
547 for t in types do
548 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
549 if not self.compiler.hardening and t == last then
550 self.add("default: /* test {t} */")
551 else
552 self.add("case {self.compiler.classid(t)}: /* test {t} */")
553 end
554 var res2 = self.call_without_varargize(propdef, t, args)
555 if res != null then self.assign(res, res2.as(not null))
556 self.add "break;"
557 end
558 if self.compiler.hardening then
559 self.add("default: /* bug */")
560 self.bugtype(args.first)
561 end
562 self.add("\}")
563 return res
564 end
565
566 redef fun adapt_signature(m, args)
567 do
568 var recv = args.first
569 for i in [0..m.msignature.arity[ do
570 var t = m.msignature.mparameters[i].mtype
571 if i == m.msignature.vararg_rank then
572 t = args[i+1].mtype
573 end
574 t = self.resolve_for(t, recv)
575 args[i+1] = self.autobox(args[i+1], t)
576 end
577 end
578
579 # FIXME: this is currently buggy since recv is not exact
580 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
581 do
582 elttype = self.resolve_for(elttype, recv)
583 return self.array_instance(varargs, elttype)
584 end
585
586 fun bugtype(recv: RuntimeVariable)
587 do
588 if recv.mtype.ctype != "val*" then return
589 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
590 self.add("show_backtrace(1);")
591 end
592
593 redef fun isset_attribute(a, recv)
594 do
595 check_recv_notnull(recv)
596
597 var types = self.collect_types(recv)
598 var res = self.new_var(bool_type)
599
600 if types.is_empty then
601 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
602 self.bugtype(recv)
603 return res
604 end
605 self.add("/* isset {a} on {recv.inspect} */")
606 self.add("switch({recv}->classid) \{")
607 var last = types.last
608 for t in types do
609 if not self.compiler.hardening and t == last then
610 self.add("default: /*{self.compiler.classid(t)}*/")
611 else
612 self.add("case {self.compiler.classid(t)}:")
613 end
614 var recv2 = self.autoadapt(recv, t)
615 var ta = a.intro.static_mtype.as(not null)
616 ta = self.resolve_for(ta, recv2)
617 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
618 if not ta isa MNullableType then
619 if ta.ctype == "val*" then
620 self.add("{res} = ({attr} != NULL);")
621 else
622 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
623 end
624 end
625 self.add("break;")
626 end
627 if self.compiler.hardening then
628 self.add("default: /* Bug */")
629 self.bugtype(recv)
630 end
631 self.add("\}")
632
633 return res
634 end
635
636 redef fun read_attribute(a, recv)
637 do
638 check_recv_notnull(recv)
639
640 var types = self.collect_types(recv)
641
642 var ret = a.intro.static_mtype.as(not null)
643 ret = self.resolve_for(ret, recv)
644 var res = self.new_var(ret)
645
646 if types.is_empty then
647 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
648 self.bugtype(recv)
649 return res
650 end
651 self.add("/* read {a} on {recv.inspect} */")
652 self.add("switch({recv}->classid) \{")
653 var last = types.last
654 for t in types do
655 if not self.compiler.hardening and t == last then
656 self.add("default: /*{self.compiler.classid(t)}*/")
657 else
658 self.add("case {self.compiler.classid(t)}:")
659 end
660 var recv2 = self.autoadapt(recv, t)
661 var ta = a.intro.static_mtype.as(not null)
662 ta = self.resolve_for(ta, recv2)
663 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
664 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value then
665 if ta.ctype == "val*" then
666 self.add("if ({res2} == NULL) \{")
667 self.add_abort("Uninitialized attribute {a.name}")
668 self.add("\}")
669 else
670 self.add("/*NOTYET isset on primitive attributes*/")
671 end
672 end
673 self.assign(res, res2)
674 self.add("break;")
675 end
676 if self.compiler.hardening then
677 self.add("default: /* Bug */")
678 self.bugtype(recv)
679 end
680 self.add("\}")
681
682 return res
683 end
684
685 redef fun write_attribute(a, recv, value)
686 do
687 check_recv_notnull(recv)
688
689 var types = self.collect_types(recv)
690
691 if types.is_empty then
692 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
693 self.bugtype(recv)
694 return
695 end
696 self.add("/* write {a} on {recv.inspect} */")
697 self.add("switch({recv}->classid) \{")
698 var last = types.last
699 for t in types do
700 if not self.compiler.hardening and t == last then
701 self.add("default: /*{self.compiler.classid(t)}*/")
702 else
703 self.add("case {self.compiler.classid(t)}:")
704 end
705 var recv2 = self.autoadapt(recv, t)
706 var ta = a.intro.static_mtype.as(not null)
707 ta = self.resolve_for(ta, recv2)
708 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
709 self.add("break;")
710 end
711 if self.compiler.hardening then
712 self.add("default: /* Bug*/")
713 self.bugtype(recv)
714 end
715 self.add("\}")
716 end
717
718 redef fun init_instance(mtype)
719 do
720 mtype = self.anchor(mtype).as(MClassType)
721 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
722 debug "problem: {mtype} was detected dead"
723 end
724 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
725 res.is_exact = true
726 return res
727 end
728
729 redef fun type_test(value, mtype, tag)
730 do
731 mtype = self.anchor(mtype)
732 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
733 debug "problem: {mtype} was detected cast-dead"
734 abort
735 end
736
737 var types = self.collect_types(value)
738 var res = self.new_var(bool_type)
739
740 self.add("/* isa {mtype} on {value.inspect} */")
741 if value.mtype.ctype != "val*" then
742 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
743 self.add("{res} = 1;")
744 else
745 self.add("{res} = 0;")
746 end
747 return res
748 end
749 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
750 self.add("if ({value} == NULL) \{")
751 if mtype isa MNullableType then
752 self.add("{res} = 1; /* isa {mtype} */")
753 else
754 self.add("{res} = 0; /* not isa {mtype} */")
755 end
756 self.add("\} else ")
757 end
758 self.add("switch({value}->classid) \{")
759 for t in types do
760 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
761 self.add("case {self.compiler.classid(t)}: /* {t} */")
762 end
763 end
764 self.add("{res} = 1;")
765 self.add("break;")
766 self.add("default:")
767 self.add("{res} = 0;")
768 self.add("\}")
769
770 return res
771 end
772
773 redef fun is_same_type_test(value1, value2)
774 do
775 var res = self.new_var(bool_type)
776 if value2.mtype.ctype == "val*" then
777 if value1.mtype.ctype == "val*" then
778 self.add "{res} = {value1}->classid == {value2}->classid;"
779 else
780 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
781 end
782 else
783 if value1.mtype.ctype == "val*" then
784 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
785 else if value1.mcasttype == value2.mcasttype then
786 self.add "{res} = 1;"
787 else
788 self.add "{res} = 0;"
789 end
790 end
791 return res
792 end
793
794 redef fun class_name_string(value)
795 do
796 var res = self.get_name("var_class_name")
797 self.add_decl("const char* {res};")
798 if value.mtype.ctype == "val*" then
799 self.add "{res} = class_names[{value}->classid];"
800 else
801 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
802 end
803 return res
804 end
805
806 redef fun equal_test(value1, value2)
807 do
808 var res = self.new_var(bool_type)
809 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
810 var tmp = value1
811 value1 = value2
812 value2 = tmp
813 end
814 if value1.mtype.ctype != "val*" then
815 if value2.mtype == value1.mtype then
816 self.add("{res} = {value1} == {value2};")
817 else if value2.mtype.ctype != "val*" then
818 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
819 else
820 var mtype1 = value1.mtype.as(MClassType)
821 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
822 self.add("if ({res}) \{")
823 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
824 self.add("\}")
825 end
826 else
827 var s = new Array[String]
828 for t in self.compiler.live_primitive_types do
829 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
830 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
831 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
832 end
833 if s.is_empty then
834 self.add("{res} = {value1} == {value2};")
835 else
836 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
837 end
838 end
839 return res
840 end
841
842 redef fun array_instance(array, elttype)
843 do
844 elttype = self.anchor(elttype)
845 var arraytype = self.get_class("Array").get_mtype([elttype])
846 var res = self.init_instance(arraytype)
847 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
848 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
849 nat.is_exact = true
850 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
851 for i in [0..array.length[ do
852 var r = self.autobox(array[i], elttype)
853 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
854 end
855 var length = self.int_instance(array.length)
856 self.send(self.get_property("with_native", arraytype), [res, nat, length])
857 self.add("\}")
858 return res
859 end
860 end
861
862 # A runtime function customized on a specific monomrph receiver type
863 private class CustomizedRuntimeFunction
864 super AbstractRuntimeFunction
865
866 redef type COMPILER: GlobalCompiler
867 redef type VISITOR: GlobalCompilerVisitor
868
869 # The considered reciever
870 # (usually is a live type but no strong guarantee)
871 var recv: MClassType
872
873 init(mmethoddef: MMethodDef, recv: MClassType)
874 do
875 super(mmethoddef)
876 self.recv = recv
877 end
878
879 redef fun build_c_name
880 do
881 var res = self.c_name_cache
882 if res != null then return res
883 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
884 res = self.mmethoddef.c_name
885 else
886 res = "{mmethoddef.c_name}__{recv.c_name}"
887 end
888 self.c_name_cache = res
889 return res
890 end
891
892 # used in the compiler worklist
893 redef fun ==(o)
894 do
895 if not o isa CustomizedRuntimeFunction then return false
896 if self.mmethoddef != o.mmethoddef then return false
897 if self.recv != o.recv then return false
898 return true
899 end
900
901 # used in the compiler work-list
902 redef fun hash do return self.mmethoddef.hash + self.recv.hash
903
904 redef fun to_s
905 do
906 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
907 return self.mmethoddef.to_s
908 else
909 return "{self.mmethoddef}@{self.recv}"
910 end
911 end
912
913 # compile the code customized for the reciever
914 redef fun compile_to_c(compiler)
915 do
916 var recv = self.recv
917 var mmethoddef = self.mmethoddef
918 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
919 print("problem: why do we compile {self} for {recv}?")
920 abort
921 end
922
923 var v = compiler.new_visitor
924 var selfvar = new RuntimeVariable("self", recv, recv)
925 if compiler.runtime_type_analysis.live_types.has(recv) then
926 selfvar.is_exact = true
927 end
928 var arguments = new Array[RuntimeVariable]
929 var frame = new Frame(v, mmethoddef, recv, arguments)
930 v.frame = frame
931
932 var sig = new FlatBuffer
933 var comment = new FlatBuffer
934 var ret = mmethoddef.msignature.return_mtype
935 if ret != null then
936 ret = v.resolve_for(ret, selfvar)
937 sig.append("{ret.ctype} ")
938 else if mmethoddef.mproperty.is_new then
939 ret = recv
940 sig.append("{ret.ctype} ")
941 else
942 sig.append("void ")
943 end
944 sig.append(self.c_name)
945 sig.append("({recv.ctype} {selfvar}")
946 comment.append("(self: {recv}")
947 arguments.add(selfvar)
948 for i in [0..mmethoddef.msignature.arity[ do
949 var mtype = mmethoddef.msignature.mparameters[i].mtype
950 if i == mmethoddef.msignature.vararg_rank then
951 mtype = v.get_class("Array").get_mtype([mtype])
952 end
953 mtype = v.resolve_for(mtype, selfvar)
954 comment.append(", {mtype}")
955 sig.append(", {mtype.ctype} p{i}")
956 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
957 arguments.add(argvar)
958 end
959 sig.append(")")
960 comment.append(")")
961 if ret != null then
962 comment.append(": {ret}")
963 end
964 compiler.header.add_decl("{sig};")
965
966 v.add_decl("/* method {self} for {comment} */")
967 v.add_decl("{sig} \{")
968 #v.add("printf(\"method {self} for {comment}\\n\");")
969 if ret != null then
970 frame.returnvar = v.new_var(ret)
971 end
972 frame.returnlabel = v.get_name("RET_LABEL")
973
974 mmethoddef.compile_inside_to_c(v, arguments)
975
976 v.add("{frame.returnlabel.as(not null)}:;")
977 if ret != null then
978 v.add("return {frame.returnvar.as(not null)};")
979 end
980 v.add("\}")
981 if not self.c_name.has_substring("VIRTUAL", 0) then compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
982 end
983
984 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
985 do
986 var ret = self.mmethoddef.msignature.return_mtype
987 if self.mmethoddef.mproperty.is_new then
988 ret = recv
989 end
990 if ret != null then
991 ret = v.resolve_for(ret, arguments.first)
992 end
993 if self.mmethoddef.can_inline(v) then
994 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
995 frame.returnlabel = v.get_name("RET_LABEL")
996 if ret != null then
997 frame.returnvar = v.new_var(ret)
998 end
999 var old_frame = v.frame
1000 v.frame = frame
1001 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1002 self.mmethoddef.compile_inside_to_c(v, arguments)
1003 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1004 v.add("\}")
1005 v.frame = old_frame
1006 return frame.returnvar
1007 end
1008 v.adapt_signature(self.mmethoddef, arguments)
1009 v.compiler.todo(self)
1010 if ret == null then
1011 v.add("{self.c_name}({arguments.join(",")});")
1012 return null
1013 else
1014 var res = v.new_var(ret)
1015 v.add("{res} = {self.c_name}({arguments.join(",")});")
1016 return res
1017 end
1018 end
1019 end