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