Automatic constructors.
[nit.git] / src / compiling / compiling_methods.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 # Compile method bodies, statments and expressions to C.
18 package compiling_methods
19
20 import compiling_base
21 private import syntax
22
23 redef class CompilerVisitor
24 # Compile a statment node
25 meth compile_stmt(n: PExpr)
26 do
27 n.prepare_compile_stmt(self)
28 var i = _variable_index
29 n.compile_stmt(self)
30 _variable_index = i
31 end
32
33 # Compile is expression node
34 meth compile_expr(n: PExpr): String
35 do
36 var i = _variable_index
37 var s = n.compile_expr(self)
38 _variable_index = i
39 if s[0] == ' ' then
40 return s
41 end
42 if s == variable(_variable_index-1) then
43 return s
44 end
45 var v = get_var
46 add_assignment(v, s)
47 return v
48 end
49
50 # Ensure that a c expression is a var
51 meth ensure_var(s: String): String
52 do
53 if s.substring(0,3) == "variable" then
54 return s
55 end
56 var v = get_var
57 add_assignment(v, s)
58 return v
59 end
60
61 # Add a assignment between a variable and an expression
62 meth add_assignment(v: String, s: String)
63 do
64 if v != s then
65 add_instr("{v} = {s};")
66 end
67 end
68
69 # Return the ith variable
70 protected meth variable(i: Int): String
71 do
72 return "variable{i}"
73 end
74
75 # Next available variable number
76 attr _variable_index: Int
77
78 # Total number of variable
79 attr _variable_index_max: Int
80
81 # Return the next available variable
82 meth get_var: String
83 do
84 var v = variable(_variable_index)
85 _variable_index = _variable_index + 1
86 if _variable_index > _variable_index_max then
87 add_decl("val_t {v};")
88 _variable_index_max = _variable_index
89 end
90 return v
91 end
92
93 # Mark the variable available
94 meth free_var(v: String)
95 do
96 # FIXME: So ugly..
97 if v == variable(_variable_index-1) then
98 _variable_index = _variable_index - 1
99 end
100 end
101
102 # Clear all status related to a method body
103 meth clear
104 do
105 _has_return = false
106 indent_level = 0
107 _variable_index = 0
108 _variable_index_max = 0
109 end
110
111 # Association between nit variable and the corrsponding c variable
112 readable attr _varnames: Map[Variable, String] = new HashMap[Variable, String]
113
114 # Is a "return" found in the method body
115 readable writable attr _has_return: Bool
116
117 # Association between parameters and the corresponding c variables
118 readable writable attr _method_params: Array[String]
119
120 # Current method compiled
121 readable writable attr _method: MMSrcMethod
122
123 # Where a nit return must branch
124 readable writable attr _return_label: String
125
126 # Where a nit break must branch
127 readable writable attr _break_label: String
128
129 # Where a nit continue must branch
130 readable writable attr _continue_label: String
131
132 # Variable where a functionnal nit return must store its value
133 readable writable attr _return_value: String
134
135 # Generate an fprintf to display an error location
136 meth printf_locate_error(node: PNode): String
137 do
138 var s = "fprintf(stderr, \""
139 if method != null then s.append(" in %s")
140 s.append(" (%s:%d)\\n\", ")
141 if method != null then s.append("LOCATE_{method.cname}, ")
142 s.append("LOCATE_{module.name}, {node.line_number});")
143 return s
144 end
145
146 redef init(module: MMSrcModule)
147 do
148 super
149 clear
150 end
151
152 meth invoke_super_init_calls_after(start_prop: MMMethod)
153 do
154 var n = method.node
155 assert n isa AConcreteInitPropdef
156
157 if n.super_init_calls.is_empty then return
158 var i = 0
159 var j = 0
160 #var s = ""
161 if start_prop != null then
162 while n.super_init_calls[i] != start_prop do
163 #s.append(" {n.super_init_calls[i]}")
164 i += 1
165 end
166 i += 1
167 #s.append(" {start_prop}")
168
169 while n.explicit_super_init_calls[j] != start_prop do
170 j += 1
171 end
172 j += 1
173 end
174 var stop_prop: MMMethod = null
175 if j < n.explicit_super_init_calls.length then
176 stop_prop = n.explicit_super_init_calls[j]
177 end
178 var l = n.super_init_calls.length
179 #s.append(" [")
180 while i < l do
181 var p = n.super_init_calls[i]
182 if p == stop_prop then break
183 var cargs = method_params
184 if p.signature.arity == 0 then
185 cargs = [method_params[0]]
186 end
187 #s.append(" {p}")
188 p.compile_call(self, cargs)
189 i += 1
190 end
191 #s.append(" ]")
192 #while i < l do
193 # s.append(" {n.super_init_calls[i]}")
194 # i += 1
195 #end
196 #if stop_prop != null then s.append(" (stop at {stop_prop})")
197 #n.printl("implicit calls in {n.method}: {s}")
198 end
199 end
200
201 ###############################################################################
202
203 redef class MMMethod
204 # Compile a call on self for given arguments
205 # Most calls are compiled with a table access,
206 # primitive calles are inlined
207 # == and != are guarded and possibly inlined
208 meth compile_call(v: CompilerVisitor, cargs: Array[String]): String
209 do
210 var i = self
211 if i isa MMSrcMethod then
212 if i isa MMMethSrcMethod and i.node isa AInternMethPropdef or
213 (i.local_class.name == (once "Array".to_symbol) and name == (once "[]".to_symbol))
214 then
215 var e = i.do_compile_inside(v, cargs)
216 return e
217 end
218 end
219 var ee = once "==".to_symbol
220 var ne = once "!=".to_symbol
221 if name == ne then
222 var eqp = signature.recv.local_class.select_method(ee)
223 var eqcall = eqp.compile_call(v, cargs)
224 return "TAG_Bool(!UNTAG_Bool({eqcall}))"
225 end
226 if global.is_init then
227 cargs = cargs.to_a
228 cargs.add("init_table /*YYY*/")
229 end
230
231 var m = "(({cname}_t)CALL({cargs[0]},{global.color_id}))"
232 var vcall = "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
233 if name == ee then
234 vcall = "UNTAG_Bool({vcall})"
235 var obj = once "Object".to_symbol
236 if i.local_class.name == obj then
237 vcall = "(({m}=={i.cname})?(IS_EQUAL_NN({cargs[0]},{cargs[1]})):({vcall}))"
238 end
239 vcall = "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
240 end
241 if signature.return_type != null then
242 return vcall
243 else
244 v.add_instr(vcall + ";")
245 return null
246 end
247 end
248
249 # Compile a call as constructor with given args
250 meth compile_constructor_call(v: CompilerVisitor, recvtype: MMType, cargs: Array[String]): String
251 do
252 var recv = v.get_var
253 v.add_instr("{recv} = NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}); /*new {recvtype}*/")
254 return recv
255 end
256
257 # Compile a call as call-next-method on self with given args
258 meth compile_super_call(v: CompilerVisitor, cargs: Array[String]): String
259 do
260 var m = "(({cname}_t)CALL({cargs[0]},{color_id_for_super}))"
261 var vcall = "{m}({cargs.join(", ")}) /*super {local_class}::{name}*/"
262 return vcall
263 end
264 end
265
266 redef class MMAttribute
267 # Compile an acces on selffor a given reciever.
268 # Result is a valid C left-value for assigment
269 meth compile_access(v: CompilerVisitor, recv: String): String
270 do
271 return "{global.attr_access}({recv}) /*{local_class}::{name}*/"
272 end
273 end
274
275 redef class MMLocalProperty
276 # Compile the property as a C property
277 meth compile_property_to_c(v: CompilerVisitor) do end
278 end
279
280 redef class MMSrcMethod
281 # Compile and declare the signature to C
282 protected meth decl_csignature(v: CompilerVisitor, args: Array[String]): String
283 do
284 var params = new Array[String]
285 var params_new: Array[String] = null
286 if global.is_init then
287 params_new = new Array[String]
288 end
289 params.add("val_t {args[0]}")
290 for i in [0..signature.arity[ do
291 var p = "val_t {args[i+1]}"
292 params.add(p)
293 if params_new != null then params_new.add(p)
294 end
295 if global.is_init then
296 params.add("int* init_table")
297 end
298 var ret: String
299 if signature.return_type != null then
300 ret = "val_t"
301 else
302 ret = "void"
303 end
304 var p = params.join(", ")
305 var s = "{ret} {cname}({p})"
306 v.add_decl("typedef {ret} (* {cname}_t)({p});")
307 v.add_decl(s + ";")
308 if params_new != null then
309 v.add_decl("val_t NEW_{cname}({params_new.join(", ")});")
310 end
311 return s
312 end
313
314 redef meth compile_property_to_c(v)
315 do
316 v.clear
317 var args = new Array[String]
318 args.add(" self")
319 for i in [0..signature.arity[ do
320 args.add(" param{i}")
321 end
322 var cs = decl_csignature(v, args)
323 v.add_decl("#define LOCATE_{cname} \"{full_name}\"")
324
325 v.add_instr("{cs} \{")
326 v.indent
327 var ctx_old = v.ctx
328 v.ctx = new CContext
329
330 var ln = 0
331 var s = self
332 if s.node != null then ln = s.node.line_number
333 v.add_decl("struct trace_t trace = \{NULL, NULL, {ln}, LOCATE_{cname}};")
334 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
335 v.add_instr("trace.file = LOCATE_{module.name};")
336 var s = do_compile_inside(v, args)
337 v.add_instr("tracehead = trace.prev;")
338 if s == null then
339 v.add_instr("return;")
340 else
341 v.add_instr("return {s};")
342 end
343
344 ctx_old.append(v.ctx)
345 v.ctx = ctx_old
346 v.unindent
347 v.add_instr("}")
348 end
349
350 # Compile the method body inline
351 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
352 end
353
354 redef class MMReadImplementationMethod
355 redef meth do_compile_inside(v, params)
356 do
357 return node.prop.compile_access(v, params[0])
358 end
359 end
360
361 redef class MMWriteImplementationMethod
362 redef meth do_compile_inside(v, params)
363 do
364 v.add_assignment(node.prop.compile_access(v, params[0]), params[1])
365 return null
366 end
367 end
368
369 redef class MMMethSrcMethod
370 redef meth do_compile_inside(v, params)
371 do
372 return node.do_compile_inside(v, self, params)
373 end
374 end
375
376 redef class MMImplicitInit
377 redef meth do_compile_inside(v, params)
378 do
379 var f = params.length - unassigned_attributes.length
380 var recv = params.first
381 for sp in super_inits do
382 assert sp isa MMMethod
383 var args_recv = [recv]
384 if sp == super_init then
385 var args = new Array[String].with_capacity(f)
386 args.add(recv)
387 for i in [1..f[ do
388 args.add(params[i])
389 end
390 sp.compile_call(v, args)
391 else
392 sp.compile_call(v, args_recv)
393 end
394 end
395 for i in [f..params.length[ do
396 var attribute = unassigned_attributes[i-f]
397 v.add_assignment(attribute.compile_access(v, recv), params[i])
398 end
399 return null
400 end
401 end
402
403 redef class MMType
404 # Compile a subtype check to self
405 # Return a NIT Bool
406 meth compile_cast(v: CompilerVisitor, recv: String): String
407 do
408 # Fixme: handle formaltypes
409 var g = local_class.global
410 return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
411 end
412
413 # Compile a cast assertion
414 meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode)
415 do
416 # Fixme: handle formaltypes
417 var g = local_class.global
418 v.add_instr("if (({recv}!=NIT_NULL) && !VAL_ISA({recv}, {g.color_id}, {g.id_id})) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
419 end
420 end
421
422 ###############################################################################
423
424 redef class AMethPropdef
425 # Compile the method body
426 meth do_compile_inside(v: CompilerVisitor, method: MMSrcMethod, params: Array[String]): String is abstract
427 end
428
429 redef class AConcreteMethPropdef
430 redef meth do_compile_inside(v, method, params)
431 do
432 var orig_meth: MMLocalProperty = method.global.intro
433 var orig_sig = orig_meth.signature_for(method.signature.recv)
434 if n_signature != null then
435 var sig = n_signature
436 assert sig isa ASignature
437 for ap in sig.n_params do
438 var cname = v.get_var
439 v.varnames[ap.variable] = cname
440 var orig_type = orig_sig[ap.position]
441 if not orig_type < ap.variable.stype then
442 # FIXME: do not test always
443 # FIXME: handle formal types
444 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
445 ap.variable.stype.compile_type_check(v, params[ap.position + 1], ap)
446 end
447 v.add_assignment(cname, params[ap.position + 1])
448 end
449 end
450 var old_method_params = v.method_params
451 var old_return_label = v.return_label
452 var old_return_value = v.return_value
453 var old_has_return = v.has_return
454
455 var itpos: String = null
456 if self isa AConcreteInitPropdef then
457 itpos = "VAL2OBJ({params[0]})->vft[{method.local_class.global.init_table_pos_id}].i"
458 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
459 v.add_instr("if (init_table[{itpos}]) return;")
460 end
461
462 v.method_params = params
463 v.has_return = false
464 v.return_label = "return_label{v.new_number}"
465 if method.signature.return_type != null then
466 v.return_value = v.get_var
467 v.free_var(v.return_value)
468 else
469 v.return_value = null
470 end
471 v.method = method
472 if self isa AConcreteInitPropdef then
473 v.invoke_super_init_calls_after(null)
474 end
475 if n_block != null then
476 v.compile_stmt(n_block)
477 end
478 if v.has_return then
479 v.add_instr("{v.return_label}: while(false);")
480 end
481 if self isa AConcreteInitPropdef then
482 v.add_instr("init_table[{itpos}] = 1;")
483 end
484 var ret = v.return_value
485 v.method_params = old_method_params
486 v.return_label = old_return_label
487 v.return_value = old_return_value
488 v.has_return = old_has_return
489 return ret
490 end
491 end
492
493 redef class ADeferredMethPropdef
494 redef meth do_compile_inside(v, method, params)
495 do
496 v.add_instr("fprintf(stderr, \"Deferred method %s called\");")
497 v.add_instr(v.printf_locate_error(self))
498 v.add_instr("nit_exit(1);")
499 if method.signature.return_type != null then
500 return("NIT_NULL")
501 else
502 return null
503 end
504 end
505 end
506
507 redef class AExternMethPropdef
508 redef meth do_compile_inside(v, method, params)
509 do
510 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
511 if n_extern != null then
512 ename = n_extern.text
513 ename = ename.substring(1, ename.length-2)
514 end
515 var sig = method.signature
516 if params.length != sig.arity + 1 then
517 printl("par:{params.length} sig:{sig.arity}")
518 end
519 var args = new Array[String]
520 args.add(sig.recv.unboxtype(params[0]))
521 for i in [0..sig.arity[ do
522 args.add(sig[i].unboxtype(params[i+1]))
523 end
524 var s = "{ename}({args.join(", ")})"
525 if sig.return_type != null then
526 return sig.return_type.boxtype(s)
527 else
528 v.add_instr("{s};")
529 return null
530 end
531 end
532 end
533
534 redef class AInternMethPropdef
535 redef meth do_compile_inside(v, method, p)
536 do
537 var c = method.local_class.name
538 var n = method.name
539 var s: String = null
540 if c == once "Int".to_symbol then
541 if n == once "object_id".to_symbol then
542 s = "{p[0]}"
543 else if n == once "unary -".to_symbol then
544 s = "TAG_Int(-UNTAG_Int({p[0]}))"
545 else if n == once "output".to_symbol then
546 v.add_instr("printf(\"%d\\n\", UNTAG_Int({p[0]}));")
547 else if n == once "ascii".to_symbol then
548 s = "TAG_Char(UNTAG_Int({p[0]}))"
549 else if n == once "succ".to_symbol then
550 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
551 else if n == once "prec".to_symbol then
552 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
553 else if n == once "to_f".to_symbol then
554 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
555 else if n == once "+".to_symbol then
556 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
557 else if n == once "-".to_symbol then
558 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
559 else if n == once "*".to_symbol then
560 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
561 else if n == once "/".to_symbol then
562 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
563 else if n == once "%".to_symbol then
564 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
565 else if n == once "<".to_symbol then
566 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
567 else if n == once ">".to_symbol then
568 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
569 else if n == once "<=".to_symbol then
570 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
571 else if n == once ">=".to_symbol then
572 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
573 else if n == once "lshift".to_symbol then
574 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
575 else if n == once "rshift".to_symbol then
576 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
577 else if n == once "==".to_symbol then
578 s = "TAG_Bool(({p[0]})==({p[1]}))"
579 else if n == once "!=".to_symbol then
580 s = "TAG_Bool(({p[0]})!=({p[1]}))"
581 end
582 else if c == once "Float".to_symbol then
583 if n == once "object_id".to_symbol then
584 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
585 else if n == once "unary -".to_symbol then
586 s = "BOX_Float(-UNBOX_Float({p[0]}))"
587 else if n == once "output".to_symbol then
588 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
589 else if n == once "to_i".to_symbol then
590 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
591 else if n == once "+".to_symbol then
592 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
593 else if n == once "-".to_symbol then
594 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
595 else if n == once "*".to_symbol then
596 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
597 else if n == once "/".to_symbol then
598 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
599 else if n == once "<".to_symbol then
600 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
601 else if n == once ">".to_symbol then
602 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
603 else if n == once "<=".to_symbol then
604 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
605 else if n == once ">=".to_symbol then
606 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
607 end
608 else if c == once "Char".to_symbol then
609 if n == once "object_id".to_symbol then
610 s = "TAG_Int(UNTAG_Char({p[0]}))"
611 else if n == once "unary -".to_symbol then
612 s = "TAG_Char(-UNTAG_Char({p[0]}))"
613 else if n == once "output".to_symbol then
614 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
615 else if n == once "ascii".to_symbol then
616 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
617 else if n == once "succ".to_symbol then
618 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
619 else if n == once "prec".to_symbol then
620 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
621 else if n == once "to_i".to_symbol then
622 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
623 else if n == once "+".to_symbol then
624 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
625 else if n == once "-".to_symbol then
626 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
627 else if n == once "*".to_symbol then
628 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
629 else if n == once "/".to_symbol then
630 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
631 else if n == once "%".to_symbol then
632 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
633 else if n == once "<".to_symbol then
634 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
635 else if n == once ">".to_symbol then
636 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
637 else if n == once "<=".to_symbol then
638 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
639 else if n == once ">=".to_symbol then
640 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
641 else if n == once "==".to_symbol then
642 s = "TAG_Bool(({p[0]})==({p[1]}))"
643 else if n == once "!=".to_symbol then
644 s = "TAG_Bool(({p[0]})!=({p[1]}))"
645 end
646 else if c == once "Bool".to_symbol then
647 if n == once "object_id".to_symbol then
648 s = "TAG_Int(UNTAG_Bool({p[0]}))"
649 else if n == once "unary -".to_symbol then
650 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
651 else if n == once "output".to_symbol then
652 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
653 else if n == once "ascii".to_symbol then
654 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
655 else if n == once "to_i".to_symbol then
656 s = "TAG_Int(UNTAG_Bool({p[0]}))"
657 else if n == once "==".to_symbol then
658 s = "TAG_Bool(({p[0]})==({p[1]}))"
659 else if n == once "!=".to_symbol then
660 s = "TAG_Bool(({p[0]})!=({p[1]}))"
661 end
662 else if c == once "NativeArray".to_symbol then
663 if n == once "object_id".to_symbol then
664 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
665 else if n == once "[]".to_symbol then
666 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
667 else if n == once "[]=".to_symbol then
668 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
669 else if n == once "copy_to".to_symbol then
670 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
671 end
672 else if c == once "NativeString".to_symbol then
673 if n == once "object_id".to_symbol then
674 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
675 else if n == once "atoi".to_symbol then
676 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
677 else if n == once "[]".to_symbol then
678 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
679 else if n == once "[]=".to_symbol then
680 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
681 else if n == once "copy_to".to_symbol then
682 v.add_instr("(void)memcpy(UNBOX_NativeString({p[1]})+UNTAG_Int({p[4]}), UNBOX_NativeString({p[0]})+UNTAG_Int({p[3]}), UNTAG_Int({p[2]}));")
683 end
684 else if n == once "object_id".to_symbol then
685 s = "TAG_Int((bigint){p[0]})"
686 else if n == once "sys".to_symbol then
687 s = "(G_sys)"
688 else if n == once "is_same_type".to_symbol then
689 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
690 else if n == once "exit".to_symbol then
691 v.add_instr("exit(UNTAG_Int({p[1]}));")
692 else if n == once "calloc_array".to_symbol then
693 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
694 else if n == once "calloc_string".to_symbol then
695 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
696
697 else
698 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
699 end
700 if method.signature.return_type != null and s == null then
701 s = "NIT_NULL /*stub*/"
702 end
703 return s
704 end
705 end
706
707 ###############################################################################
708
709 redef class PExpr
710 # Compile the node as an expression
711 # Only the visitor should call it
712 meth compile_expr(v: CompilerVisitor): String is abstract
713
714 # Prepare a call of node as a statement
715 # Only the visitor should call it
716 # It's used for local variable managment
717 meth prepare_compile_stmt(v: CompilerVisitor) do end
718
719 # Compile the node as a statement
720 # Only the visitor should call it
721 meth compile_stmt(v: CompilerVisitor) do printl("Error!")
722 end
723
724 redef class ABlockExpr
725 redef meth compile_stmt(v)
726 do
727 for n in n_expr do
728 v.compile_stmt(n)
729 end
730 end
731 end
732
733 redef class AVardeclExpr
734 redef meth prepare_compile_stmt(v)
735 do
736 var cname = v.get_var
737 v.varnames[variable] = cname
738 end
739
740 redef meth compile_stmt(v)
741 do
742 var cname = v.varnames[variable]
743 if n_expr == null then
744 var t = variable.stype
745 v.add_assignment(cname, "{t.default_cvalue} /*decl variable {variable.name}*/")
746 else
747 var e = v.compile_expr(n_expr)
748 v.add_assignment(cname, e)
749 end
750 end
751 end
752
753 redef class AReturnExpr
754 redef meth compile_stmt(v)
755 do
756 v.has_return = true
757 if n_expr != null then
758 var e = v.compile_expr(n_expr)
759 v.add_assignment(v.return_value, e)
760 end
761 v.add_instr("goto {v.return_label};")
762 end
763 end
764
765 redef class ABreakExpr
766 redef meth compile_stmt(v)
767 do
768 v.add_instr("goto {v.break_label};")
769 end
770 end
771
772 redef class AContinueExpr
773 redef meth compile_stmt(v)
774 do
775 v.add_instr("goto {v.continue_label};")
776 end
777 end
778
779 redef class AAbortExpr
780 redef meth compile_stmt(v)
781 do
782 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
783 end
784 end
785
786 redef class ADoExpr
787 redef meth compile_stmt(v)
788 do
789 if n_block != null then
790 v.compile_stmt(n_block)
791 end
792 end
793 end
794
795 redef class AIfExpr
796 redef meth compile_stmt(v)
797 do
798 var e = v.compile_expr(n_expr)
799 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
800 v.free_var(e)
801 if n_then != null then
802 v.indent
803 v.compile_stmt(n_then)
804 v.unindent
805 end
806 if n_else != null then
807 v.add_instr("} else \{ /*if*/")
808 v.indent
809 v.compile_stmt(n_else)
810 v.unindent
811 end
812 v.add_instr("}")
813 end
814 end
815
816 redef class AIfexprExpr
817 redef meth compile_expr(v)
818 do
819 var e = v.compile_expr(n_expr)
820 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
821 v.free_var(e)
822 v.indent
823 var e = v.ensure_var(v.compile_expr(n_then))
824 v.unindent
825 v.add_instr("} else \{ /*if*/")
826 v.free_var(e)
827 v.indent
828 var e2 = v.ensure_var(v.compile_expr(n_else))
829 v.add_assignment(e, e2)
830 v.unindent
831 v.add_instr("}")
832 return e
833 end
834 end
835
836 redef class AControlableBlock
837 meth compile_inside_block(v: CompilerVisitor) is abstract
838 redef meth compile_stmt(v)
839 do
840 var old_break_label = v.break_label
841 var old_continue_label = v.continue_label
842 var id = v.new_number
843 v.break_label = "break_{id}"
844 v.continue_label = "continue_{id}"
845
846 compile_inside_block(v)
847
848
849 v.break_label = old_break_label
850 v.continue_label = old_continue_label
851 end
852 end
853
854 redef class AWhileExpr
855 redef meth compile_inside_block(v)
856 do
857 v.add_instr("while (true) \{ /*while*/")
858 v.indent
859 var e = v.compile_expr(n_expr)
860 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
861 v.free_var(e)
862 if n_block != null then
863 v.compile_stmt(n_block)
864 end
865 v.add_instr("{v.continue_label}: while(0);")
866 v.unindent
867 v.add_instr("}")
868 v.add_instr("{v.break_label}: while(0);")
869 end
870 end
871
872 redef class AForExpr
873 redef meth compile_inside_block(v)
874 do
875 v.compile_stmt(n_vardecl)
876 end
877 end
878
879 redef class AForVardeclExpr
880 redef meth compile_stmt(v)
881 do
882 var e = v.compile_expr(n_expr)
883 var prop = n_expr.stype.local_class.select_method(once "iterator".to_symbol)
884 if prop == null then
885 printl("No iterator")
886 return
887 end
888 var ittype = prop.signature.return_type
889 v.free_var(e)
890 var iter = v.get_var
891 v.add_assignment(iter, prop.compile_call(v, [e]))
892 var prop2 = ittype.local_class.select_method(once "is_ok".to_symbol)
893 if prop2 == null then
894 printl("No is_ok")
895 return
896 end
897 var prop3 = ittype.local_class.select_method(once "item".to_symbol)
898 if prop3 == null then
899 printl("No item")
900 return
901 end
902 var prop4 = ittype.local_class.select_method(once "next".to_symbol)
903 if prop4 == null then
904 printl("No next")
905 return
906 end
907 v.add_instr("while (true) \{ /*for*/")
908 v.indent
909 var ok = v.get_var
910 v.add_assignment(ok, prop2.compile_call(v, [iter]))
911 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
912 v.free_var(ok)
913 var e = prop3.compile_call(v, [iter])
914 e = v.ensure_var(e)
915 v.varnames[variable] = e
916 var par = parent
917 assert par isa AForExpr
918 var n_block = par.n_block
919 if n_block != null then
920 v.compile_stmt(n_block)
921 end
922 v.add_instr("{v.continue_label}: while(0);")
923 e = prop4.compile_call(v, [iter])
924 assert e == null
925 v.unindent
926 v.add_instr("}")
927 v.add_instr("{v.break_label}: while(0);")
928 end
929 end
930
931 redef class AAssertExpr
932 redef meth compile_stmt(v)
933 do
934 var e = v.compile_expr(n_expr)
935 var s = ""
936 if n_id != null then
937 s = " '{n_id.text}' "
938 end
939 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
940 end
941 end
942
943 redef class AVarExpr
944 redef meth compile_expr(v)
945 do
946 return " {v.varnames[variable]} /*{variable.name}*/"
947 end
948 end
949
950 redef class AVarAssignExpr
951 redef meth compile_stmt(v)
952 do
953 var e = v.compile_expr(n_value)
954 v.add_assignment(v.varnames[variable], "{e} /*{variable.name}=*/")
955 end
956 end
957
958 redef class AVarReassignExpr
959 redef meth compile_stmt(v)
960 do
961 var e1 = v.varnames[variable]
962 var e2 = v.compile_expr(n_value)
963 var e3 = assign_method.compile_call(v, [e1, e2])
964 v.add_assignment(v.varnames[variable], "{e3} /*{variable.name}*/")
965 end
966 end
967
968 redef class ASelfExpr
969 redef meth compile_expr(v)
970 do
971 return v.method_params[0]
972 end
973 end
974
975 redef class AOrExpr
976 redef meth compile_expr(v)
977 do
978 var e = v.ensure_var(v.compile_expr(n_expr))
979 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
980 v.free_var(e)
981 v.indent
982 var e2 = v.compile_expr(n_expr2)
983 v.add_assignment(e, e2)
984 v.unindent
985 v.add_instr("}")
986 return e
987 end
988 end
989
990 redef class AAndExpr
991 redef meth compile_expr(v)
992 do
993 var e = v.ensure_var(v.compile_expr(n_expr))
994 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
995 v.free_var(e)
996 v.indent
997 var e2 = v.compile_expr(n_expr2)
998 v.add_assignment(e, e2)
999 v.unindent
1000 v.add_instr("}")
1001 return e
1002 end
1003 end
1004
1005 redef class ANotExpr
1006 redef meth compile_expr(v)
1007 do
1008 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1009 end
1010 end
1011
1012 redef class AEeExpr
1013 redef meth compile_expr(v)
1014 do
1015 var e = v.compile_expr(n_expr)
1016 var e2 = v.compile_expr(n_expr2)
1017 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
1018 end
1019 end
1020
1021 redef class AIsaExpr
1022 redef meth compile_expr(v)
1023 do
1024 var e = v.compile_expr(n_expr)
1025 return n_type.stype.compile_cast(v, e)
1026 end
1027 end
1028
1029 redef class AAsCastExpr
1030 redef meth compile_expr(v)
1031 do
1032 var e = v.compile_expr(n_expr)
1033 n_type.stype.compile_type_check(v, e, self)
1034 return e
1035 end
1036 end
1037
1038 redef class ATrueExpr
1039 redef meth compile_expr(v)
1040 do
1041 return " TAG_Bool(true)"
1042 end
1043 end
1044
1045 redef class AFalseExpr
1046 redef meth compile_expr(v)
1047 do
1048 return " TAG_Bool(false)"
1049 end
1050 end
1051
1052 redef class AIntExpr
1053 redef meth compile_expr(v)
1054 do
1055 return " TAG_Int({n_number.text})"
1056 end
1057 end
1058
1059 redef class AFloatExpr
1060 redef meth compile_expr(v)
1061 do
1062 return "BOX_Float({n_float.text})"
1063 end
1064 end
1065
1066 redef class ACharExpr
1067 redef meth compile_expr(v)
1068 do
1069 return " TAG_Char({n_char.text})"
1070 end
1071 end
1072
1073 redef class AStringFormExpr
1074 redef meth compile_expr(v)
1075 do
1076 var prop = stype.local_class.select_method(once "with_native".to_symbol)
1077 compute_string_info
1078 return prop.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1079 end
1080
1081 # The raw string value
1082 protected meth string_text: String is abstract
1083
1084 # The string in a C native format
1085 protected attr _cstring: String
1086
1087 # The string length in bytes
1088 protected attr _cstring_length: Int
1089
1090 # Compute _cstring and _cstring_length using string_text
1091 protected meth compute_string_info
1092 do
1093 var len = 0
1094 var str = string_text
1095 var res = new String
1096 var i = 0
1097 while i < str.length do
1098 var c = str[i]
1099 if c == '\\' then
1100 i = i + 1
1101 var c2 = str[i]
1102 if c2 != '{' and c2 != '}' then
1103 res.add(c)
1104 end
1105 c = c2
1106 end
1107 len = len + 1
1108 res.add(c)
1109 i = i + 1
1110 end
1111 _cstring = res
1112 _cstring_length = len
1113 end
1114 end
1115
1116 redef class AStringExpr
1117 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1118 end
1119 redef class AStartStringExpr
1120 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1121 end
1122 redef class AMidStringExpr
1123 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1124 end
1125 redef class AEndStringExpr
1126 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1127 end
1128
1129 redef class ASuperstringExpr
1130 redef meth compile_expr(v)
1131 do
1132 var prop = stype.local_class.select_method(once "init".to_symbol)
1133 var recv = prop.compile_constructor_call(v, stype, new Array[String])
1134
1135 var prop2 = stype.local_class.select_method(once "append".to_symbol)
1136
1137 var prop3 = stype.local_class.select_method(once "to_s".to_symbol)
1138 for ne in n_exprs do
1139 var e = v.ensure_var(v.compile_expr(ne))
1140 if ne.stype != stype then
1141 v.add_assignment(e, prop3.compile_call(v, [e]))
1142 end
1143 prop2.compile_call(v, [recv, e])
1144 end
1145
1146 return recv
1147 end
1148 end
1149
1150 redef class ANullExpr
1151 redef meth compile_expr(v)
1152 do
1153 return " NIT_NULL /*null*/"
1154 end
1155 end
1156
1157 redef class AArrayExpr
1158 redef meth compile_expr(v)
1159 do
1160 var prop = stype.local_class.select_method(once "with_capacity".to_symbol)
1161 var recv = prop.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1162
1163 var prop2 = stype.local_class.select_method(once "add".to_symbol)
1164 for ne in n_exprs do
1165 var e = v.compile_expr(ne)
1166 prop2.compile_call(v, [recv, e])
1167 end
1168 return recv
1169 end
1170 end
1171
1172 redef class ARangeExpr
1173 redef meth compile_expr(v)
1174 do
1175 var prop = stype.local_class.select_method(propname)
1176 var e = v.compile_expr(n_expr)
1177 var e2 = v.compile_expr(n_expr2)
1178 return prop.compile_constructor_call(v, stype, [e, e2])
1179 end
1180 # The constructor that must be used for the range
1181 protected meth propname: Symbol is abstract
1182 end
1183
1184 redef class ACrangeExpr
1185 redef meth propname do return once "init".to_symbol
1186 end
1187 redef class AOrangeExpr
1188 redef meth propname do return once "without_last".to_symbol
1189 end
1190
1191 redef class ASuperExpr
1192 redef meth compile_stmt(v)
1193 do
1194 var e = compile_expr(v)
1195 if e != null then v.add_instr("{e};")
1196 end
1197
1198 redef meth compile_expr(v)
1199 do
1200 var arity = v.method_params.length - 1
1201 if init_in_superclass != null then
1202 arity = init_in_superclass.signature.arity
1203 end
1204 var args = new Array[String].with_capacity(arity + 1)
1205 args.add(v.method_params[0])
1206 if n_args.length != arity then
1207 for i in [0..arity[ do
1208 args.add(v.method_params[i + 1])
1209 end
1210 else
1211 for na in n_args do
1212 args.add(v.compile_expr(na))
1213 end
1214 end
1215 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1216 if init_in_superclass != null then
1217 return init_in_superclass.compile_call(v, args)
1218 else
1219 if prop.global.is_init then args.add("init_table")
1220 return prop.compile_super_call(v, args)
1221 end
1222 end
1223 end
1224
1225 redef class AAttrExpr
1226 redef meth compile_expr(v)
1227 do
1228 var e = v.compile_expr(n_expr)
1229 return prop.compile_access(v, e)
1230 end
1231 end
1232
1233 redef class AAttrAssignExpr
1234 redef meth compile_stmt(v)
1235 do
1236 var e = v.compile_expr(n_expr)
1237 var e2 = v.compile_expr(n_value)
1238 v.add_assignment(prop.compile_access(v, e), e2)
1239 end
1240 end
1241 redef class AAttrReassignExpr
1242 redef meth compile_stmt(v)
1243 do
1244 var e1 = v.compile_expr(n_expr)
1245 var e2 = prop.compile_access(v, e1)
1246 var e3 = v.compile_expr(n_value)
1247 var e4 = assign_method.compile_call(v, [e2, e3])
1248 v.add_assignment(e2, e4)
1249 end
1250 end
1251
1252 redef class ASendExpr
1253 redef meth compile_expr(v)
1254 do
1255 var recv = v.compile_expr(n_expr)
1256 var cargs = new Array[String]
1257 cargs.add(recv)
1258 for a in arguments do
1259 cargs.add(v.compile_expr(a))
1260 end
1261
1262 var e = prop.compile_call(v, cargs)
1263 if prop.global.is_init then
1264 v.invoke_super_init_calls_after(prop)
1265 end
1266 return e
1267 end
1268
1269 redef meth compile_stmt(v)
1270 do
1271 var e = compile_expr(v)
1272 if e != null then
1273 v.add_instr(e + ";")
1274 end
1275 end
1276 end
1277
1278 redef class ASendReassignExpr
1279 redef meth compile_expr(v)
1280 do
1281 var recv = v.compile_expr(n_expr)
1282 var cargs = new Array[String]
1283 cargs.add(recv)
1284 for a in arguments do
1285 cargs.add(v.compile_expr(a))
1286 end
1287
1288 var e2 = read_prop.compile_call(v, cargs)
1289 var e3 = v.compile_expr(n_value)
1290 var e4 = assign_method.compile_call(v, [e2, e3])
1291 cargs.add(e4)
1292 return prop.compile_call(v, cargs)
1293 end
1294 end
1295
1296 redef class ANewExpr
1297 redef meth compile_expr(v)
1298 do
1299 var cargs = new Array[String]
1300 for a in arguments do
1301 cargs.add(v.compile_expr(a))
1302 end
1303 return prop.compile_constructor_call(v, stype, cargs)
1304 end
1305 end
1306
1307 redef class AProxyExpr
1308 redef meth compile_expr(v)
1309 do
1310 return v.compile_expr(n_expr)
1311 end
1312 end
1313
1314 redef class AOnceExpr
1315 redef meth compile_expr(v)
1316 do
1317 var i = v.new_number
1318 var cvar = v.get_var
1319 v.add_decl("static val_t once_value_{cvar}_{i}; static int once_bool_{cvar}_{i};")
1320 v.add_instr("if (once_bool_{cvar}_{i}) {cvar} = once_value_{cvar}_{i};")
1321 v.add_instr("else \{")
1322 v.indent
1323 v.free_var(cvar)
1324 var e = v.compile_expr(n_expr)
1325 v.add_assignment(cvar, e)
1326 v.add_instr("once_value_{cvar}_{i} = {cvar};")
1327 v.add_instr("once_bool_{cvar}_{i} = true;")
1328 v.unindent
1329 v.add_instr("}")
1330 return cvar
1331 end
1332 end