compile: new method compile_arguments_in
[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 if n == null then return
28 add_instr("/* Compile stmt {n.locate} */")
29 n.prepare_compile_stmt(self)
30 var i = cfc._variable_index
31 n.compile_stmt(self)
32 cfc._variable_index = i
33 end
34
35 # Compile is expression node
36 meth compile_expr(n: PExpr): String
37 do
38 add_instr("/* Compile expr {n.locate} */")
39 var i = cfc._variable_index
40 var s = n.compile_expr(self)
41 cfc._variable_index = i
42 if s[0] == ' ' or cfc.is_valid_variable(s) then
43 return s
44 end
45 var v = cfc.get_var("Result for expr {n.locate}")
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, comment: String): String
52 do
53 if cfc.is_valid_variable(s) then
54 add_instr("/* Ensure var {s}: {comment}*/")
55 return s
56 end
57 var v = cfc.get_var(null)
58 add_assignment(v, "{s} /* Ensure var: {comment}*/")
59 return v
60 end
61
62 # Add a assignment between a variable and an expression
63 meth add_assignment(v: String, s: String)
64 do
65 if v != s then
66 add_instr("{v} = {s};")
67 end
68 end
69
70 readable writable attr _cfc: CFunctionContext
71
72 readable writable attr _nmc: NitMethodContext
73
74 # C outputs written outside the current C function.
75 readable writable attr _out_contexts: Array[CContext] = new Array[CContext]
76
77 # Generate an fprintf to display an error location
78 meth printf_locate_error(node: PNode): String
79 do
80 var s = new Buffer.from("fprintf(stderr, \"")
81 if nmc != null then s.append(" in %s")
82 s.append(" (%s:%d)\\n\", ")
83 if nmc != null then s.append("LOCATE_{nmc.method.cname}, ")
84 s.append("LOCATE_{module.name}, {node.line_number});")
85 return s.to_s
86 end
87
88 redef init(module: MMSrcModule)
89 do
90 super
91 end
92
93 meth invoke_super_init_calls_after(start_prop: MMMethod)
94 do
95 var n = nmc.method.node
96 assert n isa AConcreteInitPropdef
97
98 if n.super_init_calls.is_empty then return
99 var i = 0
100 var j = 0
101 #var s = ""
102 if start_prop != null then
103 while n.super_init_calls[i] != start_prop do
104 #s.append(" {n.super_init_calls[i]}")
105 i += 1
106 end
107 i += 1
108 #s.append(" {start_prop}")
109
110 while n.explicit_super_init_calls[j] != start_prop do
111 j += 1
112 end
113 j += 1
114 end
115 var stop_prop: MMMethod = null
116 if j < n.explicit_super_init_calls.length then
117 stop_prop = n.explicit_super_init_calls[j]
118 end
119 var l = n.super_init_calls.length
120 #s.append(" [")
121 while i < l do
122 var p = n.super_init_calls[i]
123 if p == stop_prop then break
124 var cargs = new Array[String]
125 if p.signature.arity == 0 then
126 cargs.add(cfc.varname(nmc.method_params[0]))
127 else
128 for va in nmc.method_params do
129 cargs.add(cfc.varname(va))
130 end
131 end
132 #s.append(" {p}")
133 p.compile_call(self, cargs)
134 i += 1
135 end
136 #s.append(" ]")
137 #while i < l do
138 # s.append(" {n.super_init_calls[i]}")
139 # i += 1
140 #end
141 #if stop_prop != null then s.append(" (stop at {stop_prop})")
142 #n.printl("implicit calls in {n.method}: {s}")
143 end
144 end
145
146 # A C function currently written
147 class CFunctionContext
148 readable attr _visitor: CompilerVisitor
149
150 # Next available variable number
151 attr _variable_index: Int = 0
152
153 # Total number of variable
154 attr _variable_index_max: Int = 0
155
156 # Association between nit variable and the corrsponding c variable index
157 attr _varindexes: Map[Variable, Int] = new HashMap[Variable, Int]
158
159 # Are we currenlty in a closure definition?
160 readable writable attr _closure: NitMethodContext = null
161
162 # Return the cvariable of a Nit variable
163 meth varname(v: Variable): String
164 do
165 if v isa ClosureVariable then
166 return closure_variable(_varindexes[v])
167 else
168 return variable(_varindexes[v])
169 end
170 end
171
172 # Return the next available variable
173 meth get_var(comment: String): String
174 do
175 var v = variable(_variable_index)
176 _variable_index = _variable_index + 1
177 if _variable_index > _variable_index_max then
178 _variable_index_max = _variable_index
179 end
180 if comment != null then
181 visitor.add_instr("/* Register {v}: {comment} */")
182 end
183 return v
184 end
185
186 meth register_variable(v: Variable): String
187 do
188 _varindexes[v] = _variable_index
189 var s = get_var("Local variable")
190 return s
191 end
192
193 # Next available closure variable number
194 attr _closurevariable_index: Int = 0
195
196 meth register_closurevariable(v: ClosureVariable): String
197 do
198 var s = "closurevariable[{_closurevariable_index}]"
199 _varindexes[v] = _closurevariable_index
200 _closurevariable_index += 1
201 if _closure != null then
202 return "(closctx->{s})"
203 else
204 return s
205 end
206 end
207
208 # Return the ith cvariable
209 protected meth variable(i: Int): String
210 do
211 if closure != null then
212 var vn = once new Array[String]
213 if vn.length <= i then
214 for j in [vn.length..i] do
215 vn[j] = "(closctx->variable[{j}])"
216 end
217 end
218 return vn[i]
219 else
220 var vn = once new Array[String]
221 if vn.length <= i then
222 for j in [vn.length..i] do
223 vn[j] = "variable[{j}]"
224 end
225 end
226 return vn[i]
227 end
228 end
229
230 # Return the ith closurevariable
231 protected meth closure_variable(i: Int): String
232 do
233 if closure != null then
234 return "(closctx->closurevariable[{i}])"
235 else
236 return "closurevariable[{i}]"
237 end
238 end
239
240 # Is s a valid variable
241 protected meth is_valid_variable(s: String): Bool
242 do
243 for i in [0.._variable_index[ do
244 if s == variable(i) then return true
245 end
246 return false
247 end
248
249 # Mark the variable available
250 meth free_var(v: String)
251 do
252 # FIXME: So ugly..
253 if v == variable(_variable_index-1) then
254 _variable_index = _variable_index - 1
255 end
256 end
257
258 # Generate the local variable declarations
259 # To use at the end of the C function once all variables are known
260 meth generate_var_decls
261 do
262 if _variable_index_max > 0 then
263 visitor.add_decl("val_t variable[{_variable_index_max}];")
264 else
265 visitor.add_decl("val_t *variable = NULL;")
266 end
267 if _closurevariable_index > 0 then
268 visitor.add_decl("struct WBT_ *closurevariable[{_closurevariable_index}];")
269 else
270 visitor.add_decl("struct WBT_ **closurevariable = NULL;")
271 end
272 end
273
274 init(v: CompilerVisitor) do _visitor = v
275 end
276
277 # A Nit method currenlty compiled
278 class NitMethodContext
279 # Current method compiled
280 readable attr _method: MMSrcMethod
281
282 # Association between parameters and the corresponding variables
283 readable writable attr _method_params: Array[ParamVariable]
284
285 # Where a nit return must branch
286 readable writable attr _return_label: String
287
288 # Where a nit break must branch
289 readable writable attr _break_label: String
290
291 # Where a nit continue must branch
292 readable writable attr _continue_label: String
293
294 # Variable where a functionnal nit return must store its value
295 readable writable attr _return_value: String
296
297 # Variable where a functionnal nit break must store its value
298 readable writable attr _break_value: String
299
300 # Variable where a functionnal nit continue must store its value
301 readable writable attr _continue_value: String
302
303 init(method: MMSrcMethod)
304 do
305 _method = method
306 end
307 end
308
309 ###############################################################################
310
311 redef class ClosureVariable
312 readable writable attr _ctypename: String
313 end
314
315 redef class MMMethod
316 # Compile a call on self for given arguments
317 # Most calls are compiled with a table access,
318 # primitive calles are inlined
319 # == and != are guarded and possibly inlined
320 meth compile_call(v: CompilerVisitor, cargs: Array[String]): String
321 do
322 var i = self
323 if i isa MMSrcMethod then
324 if i isa MMMethSrcMethod and i.node isa AInternMethPropdef or
325 (i.local_class.name == (once "Array".to_symbol) and name == (once "[]".to_symbol))
326 then
327 var e = i.do_compile_inside(v, cargs)
328 return e
329 end
330 end
331 var ee = once "==".to_symbol
332 var ne = once "!=".to_symbol
333 if name == ne then
334 var eqp = signature.recv.local_class.select_method(ee)
335 var eqcall = eqp.compile_call(v, cargs)
336 return "TAG_Bool(!UNTAG_Bool({eqcall}))"
337 end
338 if global.is_init then
339 cargs = cargs.to_a
340 cargs.add("init_table /*YYY*/")
341 end
342
343 var m = "{global.meth_call}({cargs[0]})"
344 var vcall = "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
345 if name == ee then
346 vcall = "UNTAG_Bool({vcall})"
347 var obj = once "Object".to_symbol
348 if i.local_class.name == obj then
349 vcall = "(({m}=={i.cname})?(IS_EQUAL_NN({cargs[0]},{cargs[1]})):({vcall}))"
350 end
351 vcall = "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
352 end
353 if signature.return_type != null then
354 return vcall
355 else
356 v.add_instr(vcall + ";")
357 return null
358 end
359 end
360
361 # Compile a call on self for given arguments and given closures
362 meth compile_call_and_closures(v: CompilerVisitor, cargs: Array[String], clos_defs: Array[PClosureDef]): String
363 do
364 var ve: String = null
365 var arity = 0
366 if clos_defs != null then arity = clos_defs.length
367
368 # Prepare result value.
369 # In case of procedure, the return value is still used to intercept breaks
370 var old_bv = v.nmc.break_value
371 ve = v.cfc.get_var("Closure return value and escape marker")
372 v.nmc.break_value = ve
373
374 # Compile closure to c function
375 var realcargs = new Array[String] # Args to pass to the C function call
376 var closcns = new Array[String] # Closure C structure names
377 realcargs.add_all(cargs)
378 for i in [0..arity[ do
379 var cn = clos_defs[i].compile_closure(v, closure_cname(i))
380 closcns.add(cn)
381 realcargs.add(cn)
382 end
383 for i in [arity..signature.closures.length[ do
384 realcargs.add("NULL")
385 end
386
387 v.nmc.break_value = old_bv
388
389 # Call
390 var e = compile_call(v, realcargs)
391 if e != null then
392 v.add_assignment(ve, e)
393 e = ve
394 end
395
396 # Intercept returns and breaks
397 for i in [0..arity[ do
398 # A break or a return is intercepted
399 v.add_instr("if ({closcns[i]}->has_broke != NULL) \{")
400 v.indent
401 # A passtrought break or a return is intercepted: go the the next closure
402 v.add_instr("if ({closcns[i]}->has_broke != &({ve})) \{")
403 v.indent
404 if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = {closcns[i]}->has_broke; closctx->broke_value = {closcns[i]}->broke_value;")
405 v.add_instr("goto {v.nmc.return_label};")
406 v.unindent
407 # A direct break is interpected
408 if e != null then
409 # overwrite the returned value in a function
410 v.add_instr("\} else {ve} = {closcns[i]}->broke_value;")
411 else
412 # Do nothing in a procedure
413 v.add_instr("\}")
414 end
415 v.unindent
416 v.add_instr("\}")
417 end
418 return e
419 end
420
421 # Compile a call as constructor with given args
422 meth compile_constructor_call(v: CompilerVisitor, recvtype: MMType, cargs: Array[String]): String
423 do
424 return "NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}) /*new {recvtype}*/"
425 end
426
427 # Compile a call as call-next-method on self with given args
428 meth compile_super_call(v: CompilerVisitor, cargs: Array[String]): String
429 do
430 var m = "{super_meth_call}({cargs[0]})"
431 var vcall = "{m}({cargs.join(", ")}) /*super {local_class}::{name}*/"
432 return vcall
433 end
434
435 # Cname of the i-th closure C struct type
436 protected meth closure_cname(i: Int): String
437 do
438 return "FWBT_{cname}_{i}"
439 end
440 end
441
442 redef class MMAttribute
443 # Compile an acces on selffor a given reciever.
444 # Result is a valid C left-value for assigment
445 meth compile_access(v: CompilerVisitor, recv: String): String
446 do
447 return "{global.attr_access}({recv}) /*{local_class}::{name}*/"
448 end
449 end
450
451 redef class MMLocalProperty
452 # Compile the property as a C property
453 meth compile_property_to_c(v: CompilerVisitor) do end
454 end
455
456 redef class MMSrcMethod
457
458 # Compile and declare the signature to C
459 protected meth decl_csignature(v: CompilerVisitor, args: Array[String]): String
460 do
461 var params = new Array[String]
462 params.add("val_t {args[0]}")
463 for i in [0..signature.arity[ do
464 var p = "val_t {args[i+1]}"
465 params.add(p)
466 end
467
468 var first_closure_index = signature.arity + 1 # Wich parameter is the first closure
469 for i in [0..signature.closures.length[ do
470 var closcn = closure_cname(i)
471 var cs = signature.closures[i].signature # Closure signature
472 var subparams = new Array[String] # Parameters of the closure
473 subparams.add("struct WBT_ *")
474 for j in [0..cs.arity[ do
475 var p = "val_t"
476 subparams.add(p)
477 end
478 var r = "void"
479 if cs.return_type != null then r = "val_t"
480 params.add("struct WBT_ *{args[first_closure_index+i]}")
481 v.add_decl("typedef {r} (*{closcn})({subparams.join(", ")});")
482 end
483
484 if global.is_init then
485 params.add("int* init_table")
486 end
487
488 var ret: String
489 if signature.return_type != null then
490 ret = "val_t"
491 else
492 ret = "void"
493 end
494
495 var p = params.join(", ")
496 var s = "{ret} {cname}({p})"
497 v.add_decl("typedef {ret} (* {cname}_t)({p});")
498 v.add_decl(s + ";")
499 return s
500 end
501
502 redef meth compile_property_to_c(v)
503 do
504 v.cfc = new CFunctionContext(v)
505
506 var args = new Array[String]
507 args.add(" self")
508 for i in [0..signature.arity[ do
509 args.add(" param{i}")
510 end
511 for i in [0..signature.closures.length[ do
512 args.add(" wd{i}")
513 end
514 var cs = decl_csignature(v, args)
515 v.add_decl("#define LOCATE_{cname} \"{full_name}\"")
516
517 v.add_instr("{cs} \{")
518 v.indent
519 var ctx_old = v.ctx
520 v.ctx = new CContext
521
522 v.out_contexts.clear
523
524 var ln = 0
525 var s = self
526 if s.node != null then ln = s.node.line_number
527 v.add_decl("struct trace_t trace = \{NULL, NULL, {ln}, LOCATE_{cname}};")
528 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
529 v.add_instr("trace.file = LOCATE_{module.name};")
530 var s = do_compile_inside(v, args)
531 v.add_instr("tracehead = trace.prev;")
532 if s == null then
533 v.add_instr("return;")
534 else
535 v.add_instr("return {s};")
536 end
537
538 v.cfc.generate_var_decls
539
540 ctx_old.append(v.ctx)
541 v.ctx = ctx_old
542 v.unindent
543 v.add_instr("}")
544
545 for ctx in v.out_contexts do v.ctx.merge(ctx)
546 end
547
548 # Compile the method body inline
549 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
550 end
551
552 redef class MMReadImplementationMethod
553 redef meth do_compile_inside(v, params)
554 do
555 return node.prop.compile_access(v, params[0])
556 end
557 end
558
559 redef class MMWriteImplementationMethod
560 redef meth do_compile_inside(v, params)
561 do
562 v.add_assignment(node.prop.compile_access(v, params[0]), params[1])
563 return null
564 end
565 end
566
567 redef class MMMethSrcMethod
568 redef meth do_compile_inside(v, params)
569 do
570 return node.do_compile_inside(v, self, params)
571 end
572 end
573
574 redef class MMImplicitInit
575 redef meth do_compile_inside(v, params)
576 do
577 var f = params.length - unassigned_attributes.length
578 var recv = params.first
579 for sp in super_inits do
580 assert sp isa MMMethod
581 var args_recv = [recv]
582 if sp == super_init then
583 var args = new Array[String].with_capacity(f)
584 args.add(recv)
585 for i in [1..f[ do
586 args.add(params[i])
587 end
588 sp.compile_call(v, args)
589 else
590 sp.compile_call(v, args_recv)
591 end
592 end
593 for i in [f..params.length[ do
594 var attribute = unassigned_attributes[i-f]
595 v.add_assignment(attribute.compile_access(v, recv), params[i])
596 end
597 return null
598 end
599 end
600
601 redef class MMType
602 # Compile a subtype check to self
603 # Return a NIT Bool
604 meth compile_cast(v: CompilerVisitor, recv: String): String
605 do
606 # Fixme: handle formaltypes
607 var g = local_class.global
608 return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
609 end
610
611 # Compile a cast assertion
612 meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode)
613 do
614 # Fixme: handle formaltypes
615 var g = local_class.global
616 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}*/;")
617 end
618 end
619
620 ###############################################################################
621
622 redef class AMethPropdef
623 # Compile the method body
624 meth do_compile_inside(v: CompilerVisitor, method: MMSrcMethod, params: Array[String]): String is abstract
625 end
626
627 redef class PSignature
628 meth compile_parameters(v: CompilerVisitor, orig_sig: MMSignature, params: Array[String]) is abstract
629 end
630
631 redef class ASignature
632 redef meth compile_parameters(v: CompilerVisitor, orig_sig: MMSignature, params: Array[String])
633 do
634 for ap in n_params do
635 var cname = v.cfc.register_variable(ap.variable)
636 v.nmc.method_params.add(ap.variable)
637 var orig_type = orig_sig[ap.position]
638 if not orig_type < ap.variable.stype then
639 # FIXME: do not test always
640 # FIXME: handle formal types
641 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
642 ap.variable.stype.compile_type_check(v, params[ap.position], ap)
643 end
644 v.add_assignment(cname, params[ap.position])
645 end
646 for i in [0..n_closure_decls.length[ do
647 var wd = n_closure_decls[i]
648 var cname = v.cfc.register_closurevariable(wd.variable)
649 wd.variable.ctypename = v.nmc.method.closure_cname(i)
650 v.add_assignment(cname, "{params[orig_sig.arity + i]}")
651 end
652 end
653 end
654
655 redef class AConcreteMethPropdef
656 redef meth do_compile_inside(v, method, params)
657 do
658 var old_nmc = v.nmc
659 v.nmc = new NitMethodContext(method)
660
661 var selfcname = v.cfc.register_variable(self_var)
662 v.add_assignment(selfcname, params[0])
663 params.shift
664 v.nmc.method_params = [self_var]
665
666 if n_signature != null then
667 var orig_meth: MMLocalProperty = method.global.intro
668 var orig_sig = orig_meth.signature_for(method.signature.recv)
669 n_signature.compile_parameters(v, orig_sig, params)
670 end
671
672 var itpos: String = null
673 if self isa AConcreteInitPropdef then
674 itpos = "VAL2OBJ({selfcname})->vft[{method.local_class.global.init_table_pos_id}].i"
675 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
676 v.add_instr("if (init_table[{itpos}]) return;")
677 end
678
679 v.nmc.return_label = "return_label{v.new_number}"
680 v.nmc.return_value = v.cfc.get_var("Method return value and escape marker")
681 if self isa AConcreteInitPropdef then
682 v.invoke_super_init_calls_after(null)
683 end
684 v.compile_stmt(n_block)
685 v.add_instr("{v.nmc.return_label}: while(false);")
686 if self isa AConcreteInitPropdef then
687 v.add_instr("init_table[{itpos}] = 1;")
688 end
689
690 var ret: String = null
691 if method.signature.return_type != null then
692 ret = v.nmc.return_value
693 end
694
695 v.nmc = old_nmc
696 return ret
697 end
698 end
699
700 redef class ADeferredMethPropdef
701 redef meth do_compile_inside(v, method, params)
702 do
703 v.add_instr("fprintf(stderr, \"Deferred method called\");")
704 v.add_instr(v.printf_locate_error(self))
705 v.add_instr("nit_exit(1);")
706 if method.signature.return_type != null then
707 return("NIT_NULL")
708 else
709 return null
710 end
711 end
712 end
713
714 redef class AExternMethPropdef
715 redef meth do_compile_inside(v, method, params)
716 do
717 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
718 if n_extern != null then
719 ename = n_extern.text
720 ename = ename.substring(1, ename.length-2)
721 end
722 var sig = method.signature
723 if params.length != sig.arity + 1 then
724 printl("par:{params.length} sig:{sig.arity}")
725 end
726 var args = new Array[String]
727 args.add(sig.recv.unboxtype(params[0]))
728 for i in [0..sig.arity[ do
729 args.add(sig[i].unboxtype(params[i+1]))
730 end
731 var s = "{ename}({args.join(", ")})"
732 if sig.return_type != null then
733 return sig.return_type.boxtype(s)
734 else
735 v.add_instr("{s};")
736 return null
737 end
738 end
739 end
740
741 redef class AInternMethPropdef
742 redef meth do_compile_inside(v, method, p)
743 do
744 var c = method.local_class.name
745 var n = method.name
746 var s: String = null
747 if c == once "Int".to_symbol then
748 if n == once "object_id".to_symbol then
749 s = "{p[0]}"
750 else if n == once "unary -".to_symbol then
751 s = "TAG_Int(-UNTAG_Int({p[0]}))"
752 else if n == once "output".to_symbol then
753 v.add_instr("printf(\"%ld\\n\", UNTAG_Int({p[0]}));")
754 else if n == once "ascii".to_symbol then
755 s = "TAG_Char(UNTAG_Int({p[0]}))"
756 else if n == once "succ".to_symbol then
757 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
758 else if n == once "prec".to_symbol then
759 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
760 else if n == once "to_f".to_symbol then
761 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
762 else if n == once "+".to_symbol then
763 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
764 else if n == once "-".to_symbol then
765 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
766 else if n == once "*".to_symbol then
767 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
768 else if n == once "/".to_symbol then
769 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
770 else if n == once "%".to_symbol then
771 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
772 else if n == once "<".to_symbol then
773 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
774 else if n == once ">".to_symbol then
775 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
776 else if n == once "<=".to_symbol then
777 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
778 else if n == once ">=".to_symbol then
779 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
780 else if n == once "lshift".to_symbol then
781 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
782 else if n == once "rshift".to_symbol then
783 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
784 else if n == once "==".to_symbol then
785 s = "TAG_Bool(({p[0]})==({p[1]}))"
786 else if n == once "!=".to_symbol then
787 s = "TAG_Bool(({p[0]})!=({p[1]}))"
788 end
789 else if c == once "Float".to_symbol then
790 if n == once "object_id".to_symbol then
791 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
792 else if n == once "unary -".to_symbol then
793 s = "BOX_Float(-UNBOX_Float({p[0]}))"
794 else if n == once "output".to_symbol then
795 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
796 else if n == once "to_i".to_symbol then
797 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
798 else if n == once "+".to_symbol then
799 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
800 else if n == once "-".to_symbol then
801 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
802 else if n == once "*".to_symbol then
803 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
804 else if n == once "/".to_symbol then
805 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
806 else if n == once "<".to_symbol then
807 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
808 else if n == once ">".to_symbol then
809 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
810 else if n == once "<=".to_symbol then
811 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
812 else if n == once ">=".to_symbol then
813 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
814 end
815 else if c == once "Char".to_symbol then
816 if n == once "object_id".to_symbol then
817 s = "TAG_Int(UNTAG_Char({p[0]}))"
818 else if n == once "unary -".to_symbol then
819 s = "TAG_Char(-UNTAG_Char({p[0]}))"
820 else if n == once "output".to_symbol then
821 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
822 else if n == once "ascii".to_symbol then
823 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
824 else if n == once "succ".to_symbol then
825 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
826 else if n == once "prec".to_symbol then
827 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
828 else if n == once "to_i".to_symbol then
829 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
830 else if n == once "+".to_symbol then
831 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
832 else if n == once "-".to_symbol then
833 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
834 else if n == once "*".to_symbol then
835 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
836 else if n == once "/".to_symbol then
837 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
838 else if n == once "%".to_symbol then
839 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
840 else if n == once "<".to_symbol then
841 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
842 else if n == once ">".to_symbol then
843 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
844 else if n == once "<=".to_symbol then
845 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
846 else if n == once ">=".to_symbol then
847 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
848 else if n == once "==".to_symbol then
849 s = "TAG_Bool(({p[0]})==({p[1]}))"
850 else if n == once "!=".to_symbol then
851 s = "TAG_Bool(({p[0]})!=({p[1]}))"
852 end
853 else if c == once "Bool".to_symbol then
854 if n == once "object_id".to_symbol then
855 s = "TAG_Int(UNTAG_Bool({p[0]}))"
856 else if n == once "unary -".to_symbol then
857 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
858 else if n == once "output".to_symbol then
859 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
860 else if n == once "ascii".to_symbol then
861 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
862 else if n == once "to_i".to_symbol then
863 s = "TAG_Int(UNTAG_Bool({p[0]}))"
864 else if n == once "==".to_symbol then
865 s = "TAG_Bool(({p[0]})==({p[1]}))"
866 else if n == once "!=".to_symbol then
867 s = "TAG_Bool(({p[0]})!=({p[1]}))"
868 end
869 else if c == once "NativeArray".to_symbol then
870 if n == once "object_id".to_symbol then
871 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
872 else if n == once "[]".to_symbol then
873 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
874 else if n == once "[]=".to_symbol then
875 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
876 else if n == once "copy_to".to_symbol then
877 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
878 end
879 else if c == once "NativeString".to_symbol then
880 if n == once "object_id".to_symbol then
881 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
882 else if n == once "atoi".to_symbol then
883 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
884 else if n == once "[]".to_symbol then
885 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
886 else if n == once "[]=".to_symbol then
887 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
888 else if n == once "copy_to".to_symbol then
889 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]}));")
890 end
891 else if n == once "object_id".to_symbol then
892 s = "TAG_Int((bigint){p[0]})"
893 else if n == once "sys".to_symbol then
894 s = "(G_sys)"
895 else if n == once "is_same_type".to_symbol then
896 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
897 else if n == once "exit".to_symbol then
898 v.add_instr("exit(UNTAG_Int({p[1]}));")
899 else if n == once "calloc_array".to_symbol then
900 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
901 else if n == once "calloc_string".to_symbol then
902 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
903
904 else
905 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
906 end
907 if method.signature.return_type != null and s == null then
908 s = "NIT_NULL /*stub*/"
909 end
910 return s
911 end
912 end
913
914 ###############################################################################
915
916 redef class PExpr
917 # Compile the node as an expression
918 # Only the visitor should call it
919 meth compile_expr(v: CompilerVisitor): String is abstract
920
921 # Prepare a call of node as a statement
922 # Only the visitor should call it
923 # It's used for local variable managment
924 meth prepare_compile_stmt(v: CompilerVisitor) do end
925
926 # Compile the node as a statement
927 # Only the visitor should call it
928 meth compile_stmt(v: CompilerVisitor) do printl("Error!")
929 end
930
931 redef class ABlockExpr
932 redef meth compile_stmt(v)
933 do
934 for n in n_expr do
935 v.compile_stmt(n)
936 end
937 end
938 end
939
940 redef class AVardeclExpr
941 redef meth prepare_compile_stmt(v)
942 do
943 v.cfc.register_variable(variable)
944 end
945
946 redef meth compile_stmt(v)
947 do
948 var cname = v.cfc.varname(variable)
949 if n_expr == null then
950 v.add_instr("/*{cname} is variable {variable.name}*/")
951 else
952 var e = v.compile_expr(n_expr)
953 v.add_assignment(cname, e)
954 end
955 end
956 end
957
958 redef class AReturnExpr
959 redef meth compile_stmt(v)
960 do
961 if n_expr != null then
962 var e = v.compile_expr(n_expr)
963 v.add_assignment(v.nmc.return_value, e)
964 end
965 if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.return_value});")
966 v.add_instr("goto {v.nmc.return_label};")
967 end
968 end
969
970 redef class ABreakExpr
971 redef meth compile_stmt(v)
972 do
973 if n_expr != null then
974 var e = v.compile_expr(n_expr)
975 v.add_assignment(v.nmc.break_value, e)
976 end
977 if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.break_value}); closctx->broke_value = *closctx->has_broke;")
978 v.add_instr("goto {v.nmc.break_label};")
979 end
980 end
981
982 redef class AContinueExpr
983 redef meth compile_stmt(v)
984 do
985 if n_expr != null then
986 var e = v.compile_expr(n_expr)
987 v.add_assignment(v.nmc.continue_value, e)
988 end
989 v.add_instr("goto {v.nmc.continue_label};")
990 end
991 end
992
993 redef class AAbortExpr
994 redef meth compile_stmt(v)
995 do
996 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
997 end
998 end
999
1000 redef class ADoExpr
1001 redef meth compile_stmt(v)
1002 do
1003 v.compile_stmt(n_block)
1004 end
1005 end
1006
1007 redef class AIfExpr
1008 redef meth compile_stmt(v)
1009 do
1010 var e = v.compile_expr(n_expr)
1011 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
1012 v.cfc.free_var(e)
1013 if n_then != null then
1014 v.indent
1015 v.compile_stmt(n_then)
1016 v.unindent
1017 end
1018 if n_else != null then
1019 v.add_instr("} else \{ /*if*/")
1020 v.indent
1021 v.compile_stmt(n_else)
1022 v.unindent
1023 end
1024 v.add_instr("}")
1025 end
1026 end
1027
1028 redef class AIfexprExpr
1029 redef meth compile_expr(v)
1030 do
1031 var e = v.compile_expr(n_expr)
1032 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
1033 v.cfc.free_var(e)
1034 v.indent
1035 var e = v.ensure_var(v.compile_expr(n_then), "Then value")
1036 v.unindent
1037 v.add_instr("} else \{ /*if*/")
1038 v.cfc.free_var(e)
1039 v.indent
1040 var e2 = v.ensure_var(v.compile_expr(n_else), "Else value")
1041 v.add_assignment(e, e2)
1042 v.unindent
1043 v.add_instr("}")
1044 return e
1045 end
1046 end
1047
1048 redef class AControlableBlock
1049 meth compile_inside_block(v: CompilerVisitor) is abstract
1050 redef meth compile_stmt(v)
1051 do
1052 var old_break_label = v.nmc.break_label
1053 var old_continue_label = v.nmc.continue_label
1054 var id = v.new_number
1055 v.nmc.break_label = "break_{id}"
1056 v.nmc.continue_label = "continue_{id}"
1057
1058 compile_inside_block(v)
1059
1060
1061 v.nmc.break_label = old_break_label
1062 v.nmc.continue_label = old_continue_label
1063 end
1064 end
1065
1066 redef class AWhileExpr
1067 redef meth compile_inside_block(v)
1068 do
1069 v.add_instr("while (true) \{ /*while*/")
1070 v.indent
1071 var e = v.compile_expr(n_expr)
1072 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
1073 v.cfc.free_var(e)
1074 v.compile_stmt(n_block)
1075 v.add_instr("{v.nmc.continue_label}: while(0);")
1076 v.unindent
1077 v.add_instr("}")
1078 v.add_instr("{v.nmc.break_label}: while(0);")
1079 end
1080 end
1081
1082 redef class AForExpr
1083 redef meth compile_inside_block(v)
1084 do
1085 var e = v.compile_expr(n_expr)
1086 var ittype = meth_iterator.signature.return_type
1087 v.cfc.free_var(e)
1088 var iter = v.cfc.get_var("For iterator")
1089 v.add_assignment(iter, meth_iterator.compile_call(v, [e]))
1090 v.add_instr("while (true) \{ /*for*/")
1091 v.indent
1092 var ok = v.cfc.get_var("For 'is_ok' result")
1093 v.add_assignment(ok, meth_is_ok.compile_call(v, [iter]))
1094 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
1095 v.cfc.free_var(ok)
1096 var e = meth_item.compile_call(v, [iter])
1097 e = v.ensure_var(e, "For item")
1098 var cname = v.cfc.register_variable(variable)
1099 v.add_assignment(cname, e)
1100 v.compile_stmt(n_block)
1101 v.add_instr("{v.nmc.continue_label}: while(0);")
1102 e = meth_next.compile_call(v, [iter])
1103 assert e == null
1104 v.unindent
1105 v.add_instr("}")
1106 v.add_instr("{v.nmc.break_label}: while(0);")
1107 end
1108 end
1109
1110 redef class AAssertExpr
1111 redef meth compile_stmt(v)
1112 do
1113 var e = v.compile_expr(n_expr)
1114 var s = ""
1115 if n_id != null then
1116 s = " '{n_id.text}' "
1117 end
1118 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
1119 end
1120 end
1121
1122 redef class AVarExpr
1123 redef meth compile_expr(v)
1124 do
1125 return " {v.cfc.varname(variable)} /*{variable.name}*/"
1126 end
1127 end
1128
1129 redef class AVarAssignExpr
1130 redef meth compile_stmt(v)
1131 do
1132 var e = v.compile_expr(n_value)
1133 v.add_assignment(v.cfc.varname(variable), "{e} /*{variable.name}=*/")
1134 end
1135 end
1136
1137 redef class AVarReassignExpr
1138 redef meth compile_stmt(v)
1139 do
1140 var e1 = v.cfc.varname(variable)
1141 var e2 = v.compile_expr(n_value)
1142 var e3 = assign_method.compile_call(v, [e1, e2])
1143 v.add_assignment(v.cfc.varname(variable), "{e3} /*{variable.name}*/")
1144 end
1145 end
1146
1147 redef class ASelfExpr
1148 redef meth compile_expr(v)
1149 do
1150 return v.cfc.varname(v.nmc.method_params[0])
1151 end
1152 end
1153
1154 redef class AOrExpr
1155 redef meth compile_expr(v)
1156 do
1157 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'or' operand")
1158 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
1159 v.cfc.free_var(e)
1160 v.indent
1161 var e2 = v.compile_expr(n_expr2)
1162 v.add_assignment(e, e2)
1163 v.unindent
1164 v.add_instr("}")
1165 return e
1166 end
1167 end
1168
1169 redef class AAndExpr
1170 redef meth compile_expr(v)
1171 do
1172 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'and' operand")
1173 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
1174 v.cfc.free_var(e)
1175 v.indent
1176 var e2 = v.compile_expr(n_expr2)
1177 v.add_assignment(e, e2)
1178 v.unindent
1179 v.add_instr("}")
1180 return e
1181 end
1182 end
1183
1184 redef class ANotExpr
1185 redef meth compile_expr(v)
1186 do
1187 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1188 end
1189 end
1190
1191 redef class AEeExpr
1192 redef meth compile_expr(v)
1193 do
1194 var e = v.compile_expr(n_expr)
1195 var e2 = v.compile_expr(n_expr2)
1196 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
1197 end
1198 end
1199
1200 redef class AIsaExpr
1201 redef meth compile_expr(v)
1202 do
1203 var e = v.compile_expr(n_expr)
1204 return n_type.stype.compile_cast(v, e)
1205 end
1206 end
1207
1208 redef class AAsCastExpr
1209 redef meth compile_expr(v)
1210 do
1211 var e = v.compile_expr(n_expr)
1212 n_type.stype.compile_type_check(v, e, self)
1213 return e
1214 end
1215 end
1216
1217 redef class ATrueExpr
1218 redef meth compile_expr(v)
1219 do
1220 return " TAG_Bool(true)"
1221 end
1222 end
1223
1224 redef class AFalseExpr
1225 redef meth compile_expr(v)
1226 do
1227 return " TAG_Bool(false)"
1228 end
1229 end
1230
1231 redef class AIntExpr
1232 redef meth compile_expr(v)
1233 do
1234 return " TAG_Int({n_number.text})"
1235 end
1236 end
1237
1238 redef class AFloatExpr
1239 redef meth compile_expr(v)
1240 do
1241 return "BOX_Float({n_float.text})"
1242 end
1243 end
1244
1245 redef class ACharExpr
1246 redef meth compile_expr(v)
1247 do
1248 return " TAG_Char({n_char.text})"
1249 end
1250 end
1251
1252 redef class AStringFormExpr
1253 redef meth compile_expr(v)
1254 do
1255 compute_string_info
1256 var i = v.new_number
1257 var cvar = v.cfc.get_var("Once String constant")
1258 v.add_decl("static val_t once_value_{i} = NIT_NULL; /* Once value for string {cvar}*/")
1259 v.add_instr("if (once_value_{i} != NIT_NULL) {cvar} = once_value_{i};")
1260 v.add_instr("else \{")
1261 v.indent
1262 v.cfc.free_var(cvar)
1263 var e = meth_with_native.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1264 v.add_assignment(cvar, e)
1265 v.add_instr("once_value_{i} = {cvar};")
1266 v.unindent
1267 v.add_instr("}")
1268 return cvar
1269 end
1270
1271 # The raw string value
1272 protected meth string_text: String is abstract
1273
1274 # The string in a C native format
1275 protected attr _cstring: String
1276
1277 # The string length in bytes
1278 protected attr _cstring_length: Int
1279
1280 # Compute _cstring and _cstring_length using string_text
1281 protected meth compute_string_info
1282 do
1283 var len = 0
1284 var str = string_text
1285 var res = new Buffer
1286 var i = 0
1287 while i < str.length do
1288 var c = str[i]
1289 if c == '\\' then
1290 i = i + 1
1291 var c2 = str[i]
1292 if c2 != '{' and c2 != '}' then
1293 res.add(c)
1294 end
1295 c = c2
1296 end
1297 len = len + 1
1298 res.add(c)
1299 i = i + 1
1300 end
1301 _cstring = res.to_s
1302 _cstring_length = len
1303 end
1304 end
1305
1306 redef class AStringExpr
1307 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1308 end
1309 redef class AStartStringExpr
1310 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1311 end
1312 redef class AMidStringExpr
1313 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1314 end
1315 redef class AEndStringExpr
1316 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1317 end
1318
1319 redef class ASuperstringExpr
1320 redef meth compile_expr(v)
1321 do
1322 var array = meth_with_capacity.compile_constructor_call(v, atype, ["TAG_Int({n_exprs.length})"])
1323 array = v.ensure_var(array, "Array (for super-string)")
1324
1325 for ne in n_exprs do
1326 var e = v.ensure_var(v.compile_expr(ne), "super-string element")
1327 if ne.stype != stype then
1328 v.cfc.free_var(e)
1329 e = meth_to_s.compile_call(v, [e])
1330 end
1331 v.cfc.free_var(e)
1332 meth_add.compile_call(v, [array, e])
1333 end
1334
1335 return meth_to_s.compile_call(v, [array])
1336 end
1337 end
1338
1339 redef class ANullExpr
1340 redef meth compile_expr(v)
1341 do
1342 return " NIT_NULL /*null*/"
1343 end
1344 end
1345
1346 redef class AArrayExpr
1347 redef meth compile_expr(v)
1348 do
1349 var recv = meth_with_capacity.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1350 recv = v.ensure_var(recv, "Literal array")
1351
1352 for ne in n_exprs do
1353 var e = v.compile_expr(ne)
1354 meth_add.compile_call(v, [recv, e])
1355 end
1356 return recv
1357 end
1358 end
1359
1360 redef class ARangeExpr
1361 redef meth compile_expr(v)
1362 do
1363 var e = v.compile_expr(n_expr)
1364 var e2 = v.compile_expr(n_expr2)
1365 return meth_init.compile_constructor_call(v, stype, [e, e2])
1366 end
1367 end
1368
1369 redef class ASuperExpr
1370 redef meth compile_stmt(v)
1371 do
1372 var e = compile_expr(v)
1373 if e != null then v.add_instr("{e};")
1374 end
1375
1376 redef meth compile_expr(v)
1377 do
1378 var arity = v.nmc.method_params.length - 1
1379 if init_in_superclass != null then
1380 arity = init_in_superclass.signature.arity
1381 end
1382 var args = new Array[String].with_capacity(arity + 1)
1383 args.add(v.cfc.varname(v.nmc.method_params[0]))
1384 if n_args.length != arity then
1385 for i in [0..arity[ do
1386 args.add(v.cfc.varname(v.nmc.method_params[i + 1]))
1387 end
1388 else
1389 for na in n_args do
1390 args.add(v.compile_expr(na))
1391 end
1392 end
1393 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1394 if init_in_superclass != null then
1395 return init_in_superclass.compile_call(v, args)
1396 else
1397 if prop.global.is_init then args.add("init_table")
1398 return prop.compile_super_call(v, args)
1399 end
1400 end
1401 end
1402
1403 redef class AAttrExpr
1404 redef meth compile_expr(v)
1405 do
1406 var e = v.compile_expr(n_expr)
1407 return prop.compile_access(v, e)
1408 end
1409 end
1410
1411 redef class AAttrAssignExpr
1412 redef meth compile_stmt(v)
1413 do
1414 var e = v.compile_expr(n_expr)
1415 var e2 = v.compile_expr(n_value)
1416 v.add_assignment(prop.compile_access(v, e), e2)
1417 end
1418 end
1419 redef class AAttrReassignExpr
1420 redef meth compile_stmt(v)
1421 do
1422 var e1 = v.compile_expr(n_expr)
1423 var e2 = prop.compile_access(v, e1)
1424 var e3 = v.compile_expr(n_value)
1425 var e4 = assign_method.compile_call(v, [e2, e3])
1426 v.add_assignment(e2, e4)
1427 end
1428 end
1429
1430 redef class AAbsSendExpr
1431 # Compile each argument and add them to the array
1432 meth compile_arguments_in(v: CompilerVisitor, cargs: Array[String])
1433 do
1434 for a in arguments do
1435 cargs.add(v.compile_expr(a))
1436 end
1437 end
1438
1439 end
1440
1441 redef class ASendExpr
1442 redef meth compile_expr(v)
1443 do
1444 var recv = v.compile_expr(n_expr)
1445 var cargs = new Array[String]
1446 cargs.add(recv)
1447 compile_arguments_in(v, cargs)
1448
1449 var e: String
1450 if prop_signature.closures.is_empty then
1451 e = prop.compile_call(v, cargs)
1452 else
1453 e = prop.compile_call_and_closures(v, cargs, closure_defs)
1454 end
1455
1456 if prop.global.is_init then
1457 v.invoke_super_init_calls_after(prop)
1458 end
1459 return e
1460 end
1461
1462 redef meth compile_stmt(v)
1463 do
1464 var e = compile_expr(v)
1465 if e != null then
1466 v.add_instr(e + ";")
1467 end
1468 end
1469 end
1470
1471 redef class ASendReassignExpr
1472 redef meth compile_expr(v)
1473 do
1474 var recv = v.compile_expr(n_expr)
1475 var cargs = new Array[String]
1476 cargs.add(recv)
1477 compile_arguments_in(v, cargs)
1478
1479 var e2 = read_prop.compile_call(v, cargs)
1480 var e3 = v.compile_expr(n_value)
1481 var e4 = assign_method.compile_call(v, [e2, e3])
1482 cargs.add(e4)
1483 return prop.compile_call(v, cargs)
1484 end
1485 end
1486
1487 redef class ANewExpr
1488 redef meth compile_expr(v)
1489 do
1490 var cargs = new Array[String]
1491 compile_arguments_in(v, cargs)
1492 return prop.compile_constructor_call(v, stype, cargs)
1493 end
1494 end
1495
1496 redef class PClosureDef
1497 # Compile the closure definition as a function in v.out_contexts
1498 # Return the cname of the function
1499 meth compile_closure(v: CompilerVisitor, closcn: String): String is abstract
1500
1501 # Compile the closure definition inside the current C function.
1502 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
1503 end
1504
1505 redef class AClosureDef
1506 # The cname of the function
1507 readable attr _cname: String
1508
1509 redef meth compile_closure(v, closcn)
1510 do
1511 var ctx_old = v.ctx
1512 v.ctx = new CContext
1513 v.out_contexts.add(v.ctx)
1514
1515 var cfc_old = v.cfc.closure
1516 v.cfc.closure = v.nmc
1517
1518 var old_rv = v.nmc.return_value
1519 var old_bv = v.nmc.break_value
1520 if cfc_old == null then
1521 v.nmc.return_value = "closctx->{old_rv}"
1522 v.nmc.break_value = "closctx->{old_bv}"
1523 end
1524
1525 var cname = "OC_{v.nmc.method.cname}_{v.out_contexts.length}"
1526 _cname = cname
1527 var args = new Array[String]
1528 for i in [0..closure.signature.arity[ do
1529 args.add(" param{i}")
1530 end
1531
1532 var cs = decl_csignature(v, args, closcn)
1533
1534 v.add_instr("{cs} \{")
1535 v.indent
1536 var ctx_old2 = v.ctx
1537 v.ctx = new CContext
1538
1539 v.add_decl("struct trace_t trace = \{NULL, NULL, {line_number}, LOCATE_{v.nmc.method.cname}};")
1540 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
1541
1542 v.add_instr("trace.file = LOCATE_{v.module.name};")
1543 var s = do_compile_inside(v, args)
1544
1545 v.add_instr("{v.nmc.return_label}:")
1546 v.add_instr("tracehead = trace.prev;")
1547 if s == null then
1548 v.add_instr("return;")
1549 else
1550 v.add_instr("return {s};")
1551 end
1552
1553 ctx_old2.append(v.ctx)
1554 v.ctx = ctx_old2
1555 v.unindent
1556 v.add_instr("}")
1557 v.ctx = ctx_old
1558
1559 v.cfc.closure = cfc_old
1560 v.nmc.return_value = old_rv
1561 v.nmc.break_value = old_bv
1562
1563 # Build closure
1564 var closcnv = "wbclos{v.new_number}"
1565 v.add_decl("struct WBT_ {closcnv};")
1566 v.add_instr("{closcnv}.fun = (fun_t){cname};")
1567 v.add_instr("{closcnv}.has_broke = NULL;")
1568 if cfc_old != null then
1569 v.add_instr("{closcnv}.variable = closctx->variable;")
1570 v.add_instr("{closcnv}.closurevariable = closctx->closurevariable;")
1571 else
1572 v.add_instr("{closcnv}.variable = variable;")
1573 v.add_instr("{closcnv}.closurevariable = closurevariable;")
1574 end
1575
1576 return "(&{closcnv})"
1577 end
1578
1579 protected meth decl_csignature(v: CompilerVisitor, args: Array[String], closcn: String): String
1580 do
1581 var params = new Array[String]
1582 params.add("struct WBT_ *closctx")
1583 for i in [0..closure.signature.arity[ do
1584 var p = "val_t {args[i]}"
1585 params.add(p)
1586 end
1587 var ret: String
1588 if closure.signature.return_type != null then
1589 ret = "val_t"
1590 else
1591 ret = "void"
1592 end
1593 var p = params.join(", ")
1594 var s = "{ret} {cname}({p})"
1595 v.add_decl("typedef {ret} (* {cname}_t)({p});")
1596 v.add_decl(s + ";")
1597 return s
1598 end
1599
1600 redef meth do_compile_inside(v, params)
1601 do
1602 for i in [0..variables.length[ do
1603 var vacname = v.cfc.register_variable(variables[i])
1604 v.add_assignment(vacname, params[i])
1605 end
1606
1607 var old_cv = v.nmc.continue_value
1608 var old_cl = v.nmc.continue_label
1609 var old_bl = v.nmc.break_label
1610
1611 v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
1612 v.nmc.continue_label = "continue_label{v.new_number}"
1613 v.nmc.break_label = v.nmc.return_label
1614
1615 v.compile_stmt(n_expr)
1616
1617 v.add_instr("{v.nmc.continue_label}: while(false);")
1618
1619 var ret: String = null
1620 if closure.signature.return_type != null then ret = v.nmc.continue_value
1621
1622 v.nmc.continue_value = old_cv
1623 v.nmc.continue_label = old_cl
1624 v.nmc.break_label = old_bl
1625
1626 return ret
1627 end
1628 end
1629
1630 redef class PClosureDecl
1631 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
1632 end
1633 redef class AClosureDecl
1634 redef meth do_compile_inside(v, params)
1635 do
1636 if n_signature != null then n_signature.compile_parameters(v, variable.closure.signature, params)
1637
1638 var old_cv = v.nmc.continue_value
1639 var old_cl = v.nmc.continue_label
1640 var old_bl = v.nmc.break_label
1641
1642 v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
1643 v.nmc.continue_label = "continue_label{v.new_number}"
1644 v.nmc.break_label = v.nmc.return_label
1645
1646 v.compile_stmt(n_expr)
1647
1648 v.add_instr("{v.nmc.continue_label}: while(false);")
1649
1650 var ret: String = null
1651 if variable.closure.signature.return_type != null then ret = v.nmc.continue_value
1652
1653 v.nmc.continue_value = old_cv
1654 v.nmc.continue_label = old_cl
1655 v.nmc.break_label = old_bl
1656
1657 return ret
1658 end
1659 end
1660
1661 redef class AClosureCallExpr
1662 redef meth compile_expr(v)
1663 do
1664 var cargs = new Array[String]
1665 compile_arguments_in(v, cargs)
1666 var va: String = null
1667 if variable.closure.signature.return_type != null then va = v.cfc.get_var("Closure call result value")
1668
1669 if variable.closure.is_optional then
1670 v.add_instr("if({v.cfc.varname(variable)}==NULL) \{")
1671 v.indent
1672 var n = variable.decl
1673 assert n isa AClosureDecl
1674 var s = n.do_compile_inside(v, cargs)
1675 if s != null then v.add_assignment(va, s)
1676 v.unindent
1677 v.add_instr("} else \{")
1678 v.indent
1679 end
1680
1681 var ivar = v.cfc.varname(variable)
1682 var cargs2 = [ivar]
1683 cargs2.append(cargs)
1684 var s = "(({variable.ctypename})({ivar}->fun))({cargs2.join(", ")}) /* Invoke closure {variable} */"
1685 if va != null then
1686 v.add_assignment(va, s)
1687 else
1688 v.add_instr("{s};")
1689 end
1690 v.add_instr("if ({ivar}->has_broke) \{")
1691 v.indent
1692 if n_closure_defs != null and n_closure_defs.length == 1 then do
1693 n_closure_defs.first.do_compile_inside(v, null)
1694 end
1695 if v.cfc.closure == v.nmc then v.add_instr("if ({ivar}->has_broke) \{ closctx->has_broke = {ivar}->has_broke; closctx->broke_value = {ivar}->broke_value;\}")
1696 v.add_instr("goto {v.nmc.return_label};")
1697 v.unindent
1698 v.add_instr("\}")
1699
1700 if variable.closure.is_optional then
1701 v.unindent
1702 v.add_instr("\}")
1703 end
1704 return va
1705 end
1706 end
1707
1708 redef class AProxyExpr
1709 redef meth compile_expr(v)
1710 do
1711 return v.compile_expr(n_expr)
1712 end
1713 end
1714
1715 redef class AOnceExpr
1716 redef meth compile_expr(v)
1717 do
1718 var i = v.new_number
1719 var cvar = v.cfc.get_var("Once expression result")
1720 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value for {cvar}*/")
1721 v.add_instr("if (once_bool_{i}) {cvar} = once_value_{i};")
1722 v.add_instr("else \{")
1723 v.indent
1724 v.cfc.free_var(cvar)
1725 var e = v.compile_expr(n_expr)
1726 v.add_assignment(cvar, e)
1727 v.add_instr("once_value_{i} = {cvar};")
1728 v.add_instr("once_bool_{i} = true;")
1729 v.unindent
1730 v.add_instr("}")
1731 return cvar
1732 end
1733 end