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