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