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