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