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