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