Compile closure.
[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 = "(({cname}_t)CALL({cargs[0]},{global.color_id}))"
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 = "(({cname}_t)CALL({cargs[0]},{color_id_for_super}))"
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] # 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 AConcreteMethPropdef
534 redef meth do_compile_inside(v, method, params)
535 do
536 var old_nmc = v.nmc
537 v.nmc = new NitMethodContext(method)
538
539 var cname = v.cfc.register_variable(self_var)
540 v.add_assignment(cname, params[0])
541 v.nmc.method_params = [self_var]
542
543 var orig_meth: MMLocalProperty = method.global.intro
544 var orig_sig = orig_meth.signature_for(method.signature.recv)
545 if n_signature != null then
546 var sig = n_signature
547 assert sig isa ASignature
548 for ap in sig.n_params do
549 var cname = v.cfc.register_variable(ap.variable)
550 v.nmc.method_params.add(ap.variable)
551 var orig_type = orig_sig[ap.position]
552 if not orig_type < ap.variable.stype then
553 # FIXME: do not test always
554 # FIXME: handle formal types
555 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
556 ap.variable.stype.compile_type_check(v, params[ap.position + 1], ap)
557 end
558 v.add_assignment(cname, params[ap.position + 1])
559 end
560 for i in [0..sig.n_closure_decls.length[ do
561 var wd = sig.n_closure_decls[i]
562 var cname = v.cfc.register_closurevariable(wd.variable)
563 wd.variable.ctypename = "struct {method.closure_cname(i)} *"
564 v.add_assignment(cname, "{params[orig_sig.arity + i + 1]}")
565 end
566 end
567
568 var itpos: String = null
569 if self isa AConcreteInitPropdef then
570 itpos = "VAL2OBJ({params[0]})->vft[{method.local_class.global.init_table_pos_id}].i"
571 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
572 v.add_instr("if (init_table[{itpos}]) return;")
573 end
574
575 v.nmc.return_label = "return_label{v.new_number}"
576 v.nmc.return_value = v.cfc.get_var
577 if self isa AConcreteInitPropdef then
578 v.invoke_super_init_calls_after(null)
579 end
580 if n_block != null then
581 v.compile_stmt(n_block)
582 end
583 v.add_instr("{v.nmc.return_label}: while(false);")
584 if self isa AConcreteInitPropdef then
585 v.add_instr("init_table[{itpos}] = 1;")
586 end
587
588 var ret: String = null
589 if method.signature.return_type != null then
590 ret = v.nmc.return_value
591 end
592
593 v.nmc = old_nmc
594 return ret
595 end
596 end
597
598 redef class ADeferredMethPropdef
599 redef meth do_compile_inside(v, method, params)
600 do
601 v.add_instr("fprintf(stderr, \"Deferred method called\");")
602 v.add_instr(v.printf_locate_error(self))
603 v.add_instr("nit_exit(1);")
604 if method.signature.return_type != null then
605 return("NIT_NULL")
606 else
607 return null
608 end
609 end
610 end
611
612 redef class AExternMethPropdef
613 redef meth do_compile_inside(v, method, params)
614 do
615 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
616 if n_extern != null then
617 ename = n_extern.text
618 ename = ename.substring(1, ename.length-2)
619 end
620 var sig = method.signature
621 if params.length != sig.arity + 1 then
622 printl("par:{params.length} sig:{sig.arity}")
623 end
624 var args = new Array[String]
625 args.add(sig.recv.unboxtype(params[0]))
626 for i in [0..sig.arity[ do
627 args.add(sig[i].unboxtype(params[i+1]))
628 end
629 var s = "{ename}({args.join(", ")})"
630 if sig.return_type != null then
631 return sig.return_type.boxtype(s)
632 else
633 v.add_instr("{s};")
634 return null
635 end
636 end
637 end
638
639 redef class AInternMethPropdef
640 redef meth do_compile_inside(v, method, p)
641 do
642 var c = method.local_class.name
643 var n = method.name
644 var s: String = null
645 if c == once "Int".to_symbol then
646 if n == once "object_id".to_symbol then
647 s = "{p[0]}"
648 else if n == once "unary -".to_symbol then
649 s = "TAG_Int(-UNTAG_Int({p[0]}))"
650 else if n == once "output".to_symbol then
651 v.add_instr("printf(\"%ld\\n\", UNTAG_Int({p[0]}));")
652 else if n == once "ascii".to_symbol then
653 s = "TAG_Char(UNTAG_Int({p[0]}))"
654 else if n == once "succ".to_symbol then
655 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
656 else if n == once "prec".to_symbol then
657 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
658 else if n == once "to_f".to_symbol then
659 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
660 else if n == once "+".to_symbol then
661 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
662 else if n == once "-".to_symbol then
663 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
664 else if n == once "*".to_symbol then
665 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
666 else if n == once "/".to_symbol then
667 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
668 else if n == once "%".to_symbol then
669 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
670 else if n == once "<".to_symbol then
671 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
672 else if n == once ">".to_symbol then
673 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
674 else if n == once "<=".to_symbol then
675 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
676 else if n == once ">=".to_symbol then
677 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
678 else if n == once "lshift".to_symbol then
679 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
680 else if n == once "rshift".to_symbol then
681 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
682 else if n == once "==".to_symbol then
683 s = "TAG_Bool(({p[0]})==({p[1]}))"
684 else if n == once "!=".to_symbol then
685 s = "TAG_Bool(({p[0]})!=({p[1]}))"
686 end
687 else if c == once "Float".to_symbol then
688 if n == once "object_id".to_symbol then
689 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
690 else if n == once "unary -".to_symbol then
691 s = "BOX_Float(-UNBOX_Float({p[0]}))"
692 else if n == once "output".to_symbol then
693 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
694 else if n == once "to_i".to_symbol then
695 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
696 else if n == once "+".to_symbol then
697 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
698 else if n == once "-".to_symbol then
699 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
700 else if n == once "*".to_symbol then
701 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
702 else if n == once "/".to_symbol then
703 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
704 else if n == once "<".to_symbol then
705 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
706 else if n == once ">".to_symbol then
707 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
708 else if n == once "<=".to_symbol then
709 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
710 else if n == once ">=".to_symbol then
711 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
712 end
713 else if c == once "Char".to_symbol then
714 if n == once "object_id".to_symbol then
715 s = "TAG_Int(UNTAG_Char({p[0]}))"
716 else if n == once "unary -".to_symbol then
717 s = "TAG_Char(-UNTAG_Char({p[0]}))"
718 else if n == once "output".to_symbol then
719 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
720 else if n == once "ascii".to_symbol then
721 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
722 else if n == once "succ".to_symbol then
723 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
724 else if n == once "prec".to_symbol then
725 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
726 else if n == once "to_i".to_symbol then
727 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
728 else if n == once "+".to_symbol then
729 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
730 else if n == once "-".to_symbol then
731 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
732 else if n == once "*".to_symbol then
733 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
734 else if n == once "/".to_symbol then
735 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
736 else if n == once "%".to_symbol then
737 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
738 else if n == once "<".to_symbol then
739 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
740 else if n == once ">".to_symbol then
741 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
742 else if n == once "<=".to_symbol then
743 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
744 else if n == once ">=".to_symbol then
745 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
746 else if n == once "==".to_symbol then
747 s = "TAG_Bool(({p[0]})==({p[1]}))"
748 else if n == once "!=".to_symbol then
749 s = "TAG_Bool(({p[0]})!=({p[1]}))"
750 end
751 else if c == once "Bool".to_symbol then
752 if n == once "object_id".to_symbol then
753 s = "TAG_Int(UNTAG_Bool({p[0]}))"
754 else if n == once "unary -".to_symbol then
755 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
756 else if n == once "output".to_symbol then
757 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
758 else if n == once "ascii".to_symbol then
759 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
760 else if n == once "to_i".to_symbol then
761 s = "TAG_Int(UNTAG_Bool({p[0]}))"
762 else if n == once "==".to_symbol then
763 s = "TAG_Bool(({p[0]})==({p[1]}))"
764 else if n == once "!=".to_symbol then
765 s = "TAG_Bool(({p[0]})!=({p[1]}))"
766 end
767 else if c == once "NativeArray".to_symbol then
768 if n == once "object_id".to_symbol then
769 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
770 else if n == once "[]".to_symbol then
771 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
772 else if n == once "[]=".to_symbol then
773 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
774 else if n == once "copy_to".to_symbol then
775 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
776 end
777 else if c == once "NativeString".to_symbol then
778 if n == once "object_id".to_symbol then
779 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
780 else if n == once "atoi".to_symbol then
781 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
782 else if n == once "[]".to_symbol then
783 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
784 else if n == once "[]=".to_symbol then
785 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
786 else if n == once "copy_to".to_symbol then
787 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]}));")
788 end
789 else if n == once "object_id".to_symbol then
790 s = "TAG_Int((bigint){p[0]})"
791 else if n == once "sys".to_symbol then
792 s = "(G_sys)"
793 else if n == once "is_same_type".to_symbol then
794 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
795 else if n == once "exit".to_symbol then
796 v.add_instr("exit(UNTAG_Int({p[1]}));")
797 else if n == once "calloc_array".to_symbol then
798 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
799 else if n == once "calloc_string".to_symbol then
800 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
801
802 else
803 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
804 end
805 if method.signature.return_type != null and s == null then
806 s = "NIT_NULL /*stub*/"
807 end
808 return s
809 end
810 end
811
812 ###############################################################################
813
814 redef class PExpr
815 # Compile the node as an expression
816 # Only the visitor should call it
817 meth compile_expr(v: CompilerVisitor): String is abstract
818
819 # Prepare a call of node as a statement
820 # Only the visitor should call it
821 # It's used for local variable managment
822 meth prepare_compile_stmt(v: CompilerVisitor) do end
823
824 # Compile the node as a statement
825 # Only the visitor should call it
826 meth compile_stmt(v: CompilerVisitor) do printl("Error!")
827 end
828
829 redef class ABlockExpr
830 redef meth compile_stmt(v)
831 do
832 for n in n_expr do
833 v.compile_stmt(n)
834 end
835 end
836 end
837
838 redef class AVardeclExpr
839 redef meth prepare_compile_stmt(v)
840 do
841 v.cfc.register_variable(variable)
842 end
843
844 redef meth compile_stmt(v)
845 do
846 var cname = v.cfc.varname(variable)
847 if n_expr == null then
848 v.add_instr("/*{cname} is variable {variable.name}*/")
849 else
850 var e = v.compile_expr(n_expr)
851 v.add_assignment(cname, e)
852 end
853 end
854 end
855
856 redef class AReturnExpr
857 redef meth compile_stmt(v)
858 do
859 if n_expr != null then
860 var e = v.compile_expr(n_expr)
861 v.add_assignment(v.nmc.return_value, e)
862 end
863 if v.cfc.in_closure then v.add_instr("closctx->has_broke = &({v.nmc.return_value});")
864 v.add_instr("goto {v.nmc.return_label};")
865 end
866 end
867
868 redef class ABreakExpr
869 redef meth compile_stmt(v)
870 do
871 if n_expr != null then
872 var e = v.compile_expr(n_expr)
873 v.add_assignment(v.nmc.break_value, e)
874 end
875 if v.cfc.in_closure then v.add_instr("closctx->has_broke = &({v.nmc.break_value}); closctx->broke_value = *closctx->has_broke;")
876 v.add_instr("goto {v.nmc.break_label};")
877 end
878 end
879
880 redef class AContinueExpr
881 redef meth compile_stmt(v)
882 do
883 if n_expr != null then
884 var e = v.compile_expr(n_expr)
885 v.add_assignment(v.nmc.continue_value, e)
886 end
887 v.add_instr("goto {v.nmc.continue_label};")
888 end
889 end
890
891 redef class AAbortExpr
892 redef meth compile_stmt(v)
893 do
894 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
895 end
896 end
897
898 redef class ADoExpr
899 redef meth compile_stmt(v)
900 do
901 if n_block != null then
902 v.compile_stmt(n_block)
903 end
904 end
905 end
906
907 redef class AIfExpr
908 redef meth compile_stmt(v)
909 do
910 var e = v.compile_expr(n_expr)
911 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
912 v.cfc.free_var(e)
913 if n_then != null then
914 v.indent
915 v.compile_stmt(n_then)
916 v.unindent
917 end
918 if n_else != null then
919 v.add_instr("} else \{ /*if*/")
920 v.indent
921 v.compile_stmt(n_else)
922 v.unindent
923 end
924 v.add_instr("}")
925 end
926 end
927
928 redef class AIfexprExpr
929 redef meth compile_expr(v)
930 do
931 var e = v.compile_expr(n_expr)
932 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
933 v.cfc.free_var(e)
934 v.indent
935 var e = v.ensure_var(v.compile_expr(n_then))
936 v.unindent
937 v.add_instr("} else \{ /*if*/")
938 v.cfc.free_var(e)
939 v.indent
940 var e2 = v.ensure_var(v.compile_expr(n_else))
941 v.add_assignment(e, e2)
942 v.unindent
943 v.add_instr("}")
944 return e
945 end
946 end
947
948 redef class AControlableBlock
949 meth compile_inside_block(v: CompilerVisitor) is abstract
950 redef meth compile_stmt(v)
951 do
952 var old_break_label = v.nmc.break_label
953 var old_continue_label = v.nmc.continue_label
954 var id = v.new_number
955 v.nmc.break_label = "break_{id}"
956 v.nmc.continue_label = "continue_{id}"
957
958 compile_inside_block(v)
959
960
961 v.nmc.break_label = old_break_label
962 v.nmc.continue_label = old_continue_label
963 end
964 end
965
966 redef class AWhileExpr
967 redef meth compile_inside_block(v)
968 do
969 v.add_instr("while (true) \{ /*while*/")
970 v.indent
971 var e = v.compile_expr(n_expr)
972 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
973 v.cfc.free_var(e)
974 if n_block != null then
975 v.compile_stmt(n_block)
976 end
977 v.add_instr("{v.nmc.continue_label}: while(0);")
978 v.unindent
979 v.add_instr("}")
980 v.add_instr("{v.nmc.break_label}: while(0);")
981 end
982 end
983
984 redef class AForExpr
985 redef meth compile_inside_block(v)
986 do
987 v.compile_stmt(n_vardecl)
988 end
989 end
990
991 redef class AForVardeclExpr
992 redef meth compile_stmt(v)
993 do
994 var e = v.compile_expr(n_expr)
995 var prop = n_expr.stype.local_class.select_method(once "iterator".to_symbol)
996 if prop == null then
997 printl("No iterator")
998 return
999 end
1000 var ittype = prop.signature.return_type
1001 v.cfc.free_var(e)
1002 var iter = v.cfc.get_var
1003 v.add_assignment(iter, prop.compile_call(v, [e]))
1004 var prop2 = ittype.local_class.select_method(once "is_ok".to_symbol)
1005 if prop2 == null then
1006 printl("No is_ok")
1007 return
1008 end
1009 var prop3 = ittype.local_class.select_method(once "item".to_symbol)
1010 if prop3 == null then
1011 printl("No item")
1012 return
1013 end
1014 var prop4 = ittype.local_class.select_method(once "next".to_symbol)
1015 if prop4 == null then
1016 printl("No next")
1017 return
1018 end
1019 v.add_instr("while (true) \{ /*for*/")
1020 v.indent
1021 var ok = v.cfc.get_var
1022 v.add_assignment(ok, prop2.compile_call(v, [iter]))
1023 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
1024 v.cfc.free_var(ok)
1025 var e = prop3.compile_call(v, [iter])
1026 e = v.ensure_var(e)
1027 var cname = v.cfc.register_variable(variable)
1028 v.add_assignment(cname, e)
1029 var par = parent
1030 assert par isa AForExpr
1031 var n_block = par.n_block
1032 if n_block != null then
1033 v.compile_stmt(n_block)
1034 end
1035 v.add_instr("{v.nmc.continue_label}: while(0);")
1036 e = prop4.compile_call(v, [iter])
1037 assert e == null
1038 v.unindent
1039 v.add_instr("}")
1040 v.add_instr("{v.nmc.break_label}: while(0);")
1041 end
1042 end
1043
1044 redef class AAssertExpr
1045 redef meth compile_stmt(v)
1046 do
1047 var e = v.compile_expr(n_expr)
1048 var s = ""
1049 if n_id != null then
1050 s = " '{n_id.text}' "
1051 end
1052 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
1053 end
1054 end
1055
1056 redef class AVarExpr
1057 redef meth compile_expr(v)
1058 do
1059 return " {v.cfc.varname(variable)} /*{variable.name}*/"
1060 end
1061 end
1062
1063 redef class AVarAssignExpr
1064 redef meth compile_stmt(v)
1065 do
1066 var e = v.compile_expr(n_value)
1067 v.add_assignment(v.cfc.varname(variable), "{e} /*{variable.name}=*/")
1068 end
1069 end
1070
1071 redef class AVarReassignExpr
1072 redef meth compile_stmt(v)
1073 do
1074 var e1 = v.cfc.varname(variable)
1075 var e2 = v.compile_expr(n_value)
1076 var e3 = assign_method.compile_call(v, [e1, e2])
1077 v.add_assignment(v.cfc.varname(variable), "{e3} /*{variable.name}*/")
1078 end
1079 end
1080
1081 redef class ASelfExpr
1082 redef meth compile_expr(v)
1083 do
1084 return v.cfc.varname(v.nmc.method_params[0])
1085 end
1086 end
1087
1088 redef class AOrExpr
1089 redef meth compile_expr(v)
1090 do
1091 var e = v.ensure_var(v.compile_expr(n_expr))
1092 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
1093 v.cfc.free_var(e)
1094 v.indent
1095 var e2 = v.compile_expr(n_expr2)
1096 v.add_assignment(e, e2)
1097 v.unindent
1098 v.add_instr("}")
1099 return e
1100 end
1101 end
1102
1103 redef class AAndExpr
1104 redef meth compile_expr(v)
1105 do
1106 var e = v.ensure_var(v.compile_expr(n_expr))
1107 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
1108 v.cfc.free_var(e)
1109 v.indent
1110 var e2 = v.compile_expr(n_expr2)
1111 v.add_assignment(e, e2)
1112 v.unindent
1113 v.add_instr("}")
1114 return e
1115 end
1116 end
1117
1118 redef class ANotExpr
1119 redef meth compile_expr(v)
1120 do
1121 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1122 end
1123 end
1124
1125 redef class AEeExpr
1126 redef meth compile_expr(v)
1127 do
1128 var e = v.compile_expr(n_expr)
1129 var e2 = v.compile_expr(n_expr2)
1130 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
1131 end
1132 end
1133
1134 redef class AIsaExpr
1135 redef meth compile_expr(v)
1136 do
1137 var e = v.compile_expr(n_expr)
1138 return n_type.stype.compile_cast(v, e)
1139 end
1140 end
1141
1142 redef class AAsCastExpr
1143 redef meth compile_expr(v)
1144 do
1145 var e = v.compile_expr(n_expr)
1146 n_type.stype.compile_type_check(v, e, self)
1147 return e
1148 end
1149 end
1150
1151 redef class ATrueExpr
1152 redef meth compile_expr(v)
1153 do
1154 return " TAG_Bool(true)"
1155 end
1156 end
1157
1158 redef class AFalseExpr
1159 redef meth compile_expr(v)
1160 do
1161 return " TAG_Bool(false)"
1162 end
1163 end
1164
1165 redef class AIntExpr
1166 redef meth compile_expr(v)
1167 do
1168 return " TAG_Int({n_number.text})"
1169 end
1170 end
1171
1172 redef class AFloatExpr
1173 redef meth compile_expr(v)
1174 do
1175 return "BOX_Float({n_float.text})"
1176 end
1177 end
1178
1179 redef class ACharExpr
1180 redef meth compile_expr(v)
1181 do
1182 return " TAG_Char({n_char.text})"
1183 end
1184 end
1185
1186 redef class AStringFormExpr
1187 redef meth compile_expr(v)
1188 do
1189 var prop = stype.local_class.select_method(once "with_native".to_symbol)
1190 compute_string_info
1191 return prop.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1192 end
1193
1194 # The raw string value
1195 protected meth string_text: String is abstract
1196
1197 # The string in a C native format
1198 protected attr _cstring: String
1199
1200 # The string length in bytes
1201 protected attr _cstring_length: Int
1202
1203 # Compute _cstring and _cstring_length using string_text
1204 protected meth compute_string_info
1205 do
1206 var len = 0
1207 var str = string_text
1208 var res = new String
1209 var i = 0
1210 while i < str.length do
1211 var c = str[i]
1212 if c == '\\' then
1213 i = i + 1
1214 var c2 = str[i]
1215 if c2 != '{' and c2 != '}' then
1216 res.add(c)
1217 end
1218 c = c2
1219 end
1220 len = len + 1
1221 res.add(c)
1222 i = i + 1
1223 end
1224 _cstring = res
1225 _cstring_length = len
1226 end
1227 end
1228
1229 redef class AStringExpr
1230 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1231 end
1232 redef class AStartStringExpr
1233 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1234 end
1235 redef class AMidStringExpr
1236 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1237 end
1238 redef class AEndStringExpr
1239 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1240 end
1241
1242 redef class ASuperstringExpr
1243 redef meth compile_expr(v)
1244 do
1245 var prop = stype.local_class.select_method(once "init".to_symbol)
1246 var recv = prop.compile_constructor_call(v, stype, new Array[String])
1247
1248 var prop2 = stype.local_class.select_method(once "append".to_symbol)
1249
1250 var prop3 = stype.local_class.select_method(once "to_s".to_symbol)
1251 for ne in n_exprs do
1252 var e = v.ensure_var(v.compile_expr(ne))
1253 if ne.stype != stype then
1254 v.add_assignment(e, prop3.compile_call(v, [e]))
1255 end
1256 prop2.compile_call(v, [recv, e])
1257 end
1258
1259 return recv
1260 end
1261 end
1262
1263 redef class ANullExpr
1264 redef meth compile_expr(v)
1265 do
1266 return " NIT_NULL /*null*/"
1267 end
1268 end
1269
1270 redef class AArrayExpr
1271 redef meth compile_expr(v)
1272 do
1273 var prop = stype.local_class.select_method(once "with_capacity".to_symbol)
1274 var recv = prop.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1275
1276 var prop2 = stype.local_class.select_method(once "add".to_symbol)
1277 for ne in n_exprs do
1278 var e = v.compile_expr(ne)
1279 prop2.compile_call(v, [recv, e])
1280 end
1281 return recv
1282 end
1283 end
1284
1285 redef class ARangeExpr
1286 redef meth compile_expr(v)
1287 do
1288 var prop = stype.local_class.select_method(propname)
1289 var e = v.compile_expr(n_expr)
1290 var e2 = v.compile_expr(n_expr2)
1291 return prop.compile_constructor_call(v, stype, [e, e2])
1292 end
1293 # The constructor that must be used for the range
1294 protected meth propname: Symbol is abstract
1295 end
1296
1297 redef class ACrangeExpr
1298 redef meth propname do return once "init".to_symbol
1299 end
1300 redef class AOrangeExpr
1301 redef meth propname do return once "without_last".to_symbol
1302 end
1303
1304 redef class ASuperExpr
1305 redef meth compile_stmt(v)
1306 do
1307 var e = compile_expr(v)
1308 if e != null then v.add_instr("{e};")
1309 end
1310
1311 redef meth compile_expr(v)
1312 do
1313 var arity = v.nmc.method_params.length - 1
1314 if init_in_superclass != null then
1315 arity = init_in_superclass.signature.arity
1316 end
1317 var args = new Array[String].with_capacity(arity + 1)
1318 args.add(v.cfc.varname(v.nmc.method_params[0]))
1319 if n_args.length != arity then
1320 for i in [0..arity[ do
1321 args.add(v.cfc.varname(v.nmc.method_params[i + 1]))
1322 end
1323 else
1324 for na in n_args do
1325 args.add(v.compile_expr(na))
1326 end
1327 end
1328 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1329 if init_in_superclass != null then
1330 return init_in_superclass.compile_call(v, args)
1331 else
1332 if prop.global.is_init then args.add("init_table")
1333 return prop.compile_super_call(v, args)
1334 end
1335 end
1336 end
1337
1338 redef class AAttrExpr
1339 redef meth compile_expr(v)
1340 do
1341 var e = v.compile_expr(n_expr)
1342 return prop.compile_access(v, e)
1343 end
1344 end
1345
1346 redef class AAttrAssignExpr
1347 redef meth compile_stmt(v)
1348 do
1349 var e = v.compile_expr(n_expr)
1350 var e2 = v.compile_expr(n_value)
1351 v.add_assignment(prop.compile_access(v, e), e2)
1352 end
1353 end
1354 redef class AAttrReassignExpr
1355 redef meth compile_stmt(v)
1356 do
1357 var e1 = v.compile_expr(n_expr)
1358 var e2 = prop.compile_access(v, e1)
1359 var e3 = v.compile_expr(n_value)
1360 var e4 = assign_method.compile_call(v, [e2, e3])
1361 v.add_assignment(e2, e4)
1362 end
1363 end
1364
1365 redef class ASendExpr
1366 redef meth compile_expr(v)
1367 do
1368 var recv = v.compile_expr(n_expr)
1369 var cargs = new Array[String]
1370 cargs.add(recv)
1371 for a in arguments do
1372 cargs.add(v.compile_expr(a))
1373 end
1374
1375 var cd = closure_defs
1376 var e: String
1377 if cd == null then
1378 e = prop.compile_call(v, cargs)
1379 else
1380 var closcns = new Array[String]
1381 var ve: String = null
1382
1383 # Prepare result value.
1384 # In case of procedure, the return value is still used to intercept breaks
1385 var old_bv = v.nmc.break_value
1386 ve = v.cfc.get_var
1387 v.nmc.break_value = ve
1388
1389 # Compile closure to c function
1390 for i in [0..cd.length[ do
1391 var cn = cd[i].compile_closure(v, prop.closure_cname(i))
1392 closcns.add(cn)
1393 cargs.add(cn)
1394 end
1395
1396 v.nmc.break_value = old_bv
1397
1398 # Call
1399 e = prop.compile_call(v, cargs)
1400 if e != null then
1401 v.add_assignment(ve, e)
1402 e = ve
1403 end
1404
1405 # Intercept returns and breaks
1406 for i in [0..cd.length[ do
1407 # A break or a return is intercepted
1408 v.add_instr("if ({closcns[i]}->has_broke != NULL) \{")
1409 v.indent
1410 # A passtrought break or a return is intercepted: go the the next closure
1411 v.add_instr("if ({closcns[i]}->has_broke != &({ve})) \{")
1412 v.indent
1413 if v.cfc.in_closure then v.add_instr("closctx->has_broke = {closcns[i]}->has_broke; closctx->broke_value = {closcns[i]}->broke_value;")
1414 v.add_instr("goto {v.nmc.return_label};")
1415 v.unindent
1416 # A direct break is interpected
1417 if e != null then
1418 # overwrite the returned value in a function
1419 v.add_instr("\} else {ve} = {closcns[i]}->broke_value;")
1420 else
1421 # Do nothing in a procedure
1422 v.add_instr("\}")
1423 end
1424 v.unindent
1425 v.add_instr("\}")
1426 end
1427 end
1428
1429 if prop.global.is_init then
1430 v.invoke_super_init_calls_after(prop)
1431 end
1432 return e
1433 end
1434
1435 redef meth compile_stmt(v)
1436 do
1437 var e = compile_expr(v)
1438 if e != null then
1439 v.add_instr(e + ";")
1440 end
1441 end
1442 end
1443
1444 redef class ASendReassignExpr
1445 redef meth compile_expr(v)
1446 do
1447 var recv = v.compile_expr(n_expr)
1448 var cargs = new Array[String]
1449 cargs.add(recv)
1450 for a in arguments do
1451 cargs.add(v.compile_expr(a))
1452 end
1453
1454 var e2 = read_prop.compile_call(v, cargs)
1455 var e3 = v.compile_expr(n_value)
1456 var e4 = assign_method.compile_call(v, [e2, e3])
1457 cargs.add(e4)
1458 return prop.compile_call(v, cargs)
1459 end
1460 end
1461
1462 redef class ANewExpr
1463 redef meth compile_expr(v)
1464 do
1465 var cargs = new Array[String]
1466 for a in arguments do
1467 cargs.add(v.compile_expr(a))
1468 end
1469 return prop.compile_constructor_call(v, stype, cargs)
1470 end
1471 end
1472
1473 redef class PClosureDef
1474 # Compile the closure definition as a function in v.out_contexts
1475 # Return the cname of the function
1476 meth compile_closure(v: CompilerVisitor, closcn: String): String is abstract
1477
1478 # Compile the closure definition inside the current C function.
1479 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
1480 end
1481
1482 redef class AClosureDef
1483 # The cname of the function
1484 readable attr _cname: String
1485
1486 redef meth compile_closure(v, closcn)
1487 do
1488 var ctx_old = v.ctx
1489 v.ctx = new CContext
1490 v.out_contexts.add(v.ctx)
1491
1492 var cfc_old = v.cfc.in_closure
1493 v.cfc.in_closure = true
1494
1495 var old_rv = v.nmc.return_value
1496 var old_bv = v.nmc.break_value
1497 if not cfc_old then
1498 v.nmc.return_value = "closctx->{old_rv}"
1499 v.nmc.break_value = "closctx->{old_bv}"
1500 end
1501
1502 var cname = "OC_{v.nmc.method.cname}_{v.out_contexts.length}"
1503 _cname = cname
1504 var args = new Array[String]
1505 for i in [0..signature.arity[ do
1506 args.add(" param{i}")
1507 end
1508
1509 var cs = decl_csignature(v, args, closcn)
1510
1511 v.add_instr("{cs} \{")
1512 v.indent
1513 var ctx_old2 = v.ctx
1514 v.ctx = new CContext
1515
1516 v.add_decl("struct trace_t trace = \{NULL, NULL, {line_number}, LOCATE_{v.nmc.method.cname}};")
1517 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
1518
1519 v.add_instr("trace.file = LOCATE_{v.module.name};")
1520 var s = do_compile_inside(v, args)
1521
1522 v.add_instr("{v.nmc.return_label}:")
1523 v.add_instr("tracehead = trace.prev;")
1524 if s == null then
1525 v.add_instr("return;")
1526 else
1527 v.add_instr("return {s};")
1528 end
1529
1530 ctx_old2.append(v.ctx)
1531 v.ctx = ctx_old2
1532 v.unindent
1533 v.add_instr("}")
1534 v.ctx = ctx_old
1535
1536 v.cfc.in_closure = cfc_old
1537 v.nmc.return_value = old_rv
1538 v.nmc.break_value = old_bv
1539
1540 # Build closure
1541 var closcnv = "wbclos{v.new_number}"
1542 v.add_decl("struct {closcn} {closcnv} = \{{cname}, NULL\};")
1543 if cfc_old then
1544 v.add_instr("{closcnv}.variable = closctx->variable;")
1545 v.add_instr("{closcnv}.closurevariable = closctx->closurevariable;")
1546 else
1547 v.add_instr("{closcnv}.variable = variable;")
1548 v.add_instr("{closcnv}.closurevariable = closurevariable;")
1549 end
1550
1551 return "(&{closcnv})"
1552 end
1553
1554 protected meth decl_csignature(v: CompilerVisitor, args: Array[String], closcn: String): String
1555 do
1556 var params = new Array[String]
1557 params.add("struct {closcn}* closctx")
1558 for i in [0..signature.arity[ do
1559 var p = "val_t {args[i]}"
1560 params.add(p)
1561 end
1562 var ret: String
1563 if signature.return_type != null then
1564 ret = "val_t"
1565 else
1566 ret = "void"
1567 end
1568 var p = params.join(", ")
1569 var s = "{ret} {cname}({p})"
1570 v.add_decl("struct {closcn};")
1571 v.add_decl("typedef {ret} (* {cname}_t)({p});")
1572 v.add_decl(s + ";")
1573 return s
1574 end
1575
1576 redef meth do_compile_inside(v, params)
1577 do
1578 for i in [0..variables.length[ do
1579 var vacname = v.cfc.register_variable(variables[i])
1580 v.add_assignment(vacname, params[i])
1581 end
1582
1583 var old_cv = v.nmc.continue_value
1584 var old_cl = v.nmc.continue_label
1585 var old_bl = v.nmc.break_label
1586
1587 v.nmc.continue_value = v.cfc.get_var
1588 v.nmc.continue_label = "continue_label{v.new_number}"
1589 v.nmc.break_label = v.nmc.return_label
1590
1591 if n_expr != null then v.compile_stmt(n_expr)
1592
1593 v.add_instr("{v.nmc.continue_label}: while(false);")
1594
1595 var ret: String = null
1596 if signature.return_type != null then ret = v.nmc.continue_value
1597
1598 v.nmc.continue_value = old_cv
1599 v.nmc.continue_label = old_cl
1600 v.nmc.break_label = old_bl
1601
1602 return ret
1603 end
1604 end
1605
1606 redef class AClosureCallExpr
1607 redef meth compile_expr(v)
1608 do
1609 var cargs = new Array[String]
1610 var ivar = "(({variable.ctypename})({v.cfc.varname(variable)}))"
1611 cargs.add(ivar)
1612 for a in arguments do
1613 cargs.add(v.compile_expr(a))
1614 end
1615 var s = "({ivar}->fun({cargs.join(", ")})) /* Invoke closure {variable} */"
1616 var va: String = null
1617 if variable.signature.return_type != null then
1618 va = v.cfc.get_var
1619 v.add_assignment(va, s)
1620 else
1621 v.add_instr("{s};")
1622 end
1623 v.add_instr("if ({ivar}->has_broke) \{")
1624 v.indent
1625 if n_closure_defs != null and n_closure_defs.length == 1 then do
1626 n_closure_defs.first.do_compile_inside(v, null)
1627 end
1628 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;\}")
1629 v.add_instr("goto {v.nmc.return_label};")
1630 v.unindent
1631 v.add_instr("\}")
1632 return va
1633 end
1634 end
1635
1636 redef class AProxyExpr
1637 redef meth compile_expr(v)
1638 do
1639 return v.compile_expr(n_expr)
1640 end
1641 end
1642
1643 redef class AOnceExpr
1644 redef meth compile_expr(v)
1645 do
1646 var i = v.new_number
1647 var cvar = v.cfc.get_var
1648 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value for {cvar}*/")
1649 v.add_instr("if (once_bool_{i}) {cvar} = once_value_{i};")
1650 v.add_instr("else \{")
1651 v.indent
1652 v.cfc.free_var(cvar)
1653 var e = v.compile_expr(n_expr)
1654 v.add_assignment(cvar, e)
1655 v.add_instr("once_value_{i} = {cvar};")
1656 v.add_instr("once_bool_{i} = true;")
1657 v.unindent
1658 v.add_instr("}")
1659 return cvar
1660 end
1661 end