syntax: 'meth' -> 'fun', 'attr' -> 'var'
[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 fun compile_stmt(n: nullable 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 fun 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 fun 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 fun 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 var _cfc: nullable CFunctionContext
71
72 readable writable var _nmc: nullable NitMethodContext
73
74 # C outputs written outside the current C function.
75 readable writable var _out_contexts: Array[CContext] = new Array[CContext]
76
77 # Generate an fprintf to display an error location
78 fun 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 fun invoke_super_init_calls_after(start_prop: nullable 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: nullable 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.as(not null) 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 var _visitor: CompilerVisitor
144
145 # Next available variable number
146 var _variable_index: Int = 0
147
148 # Total number of variable
149 var _variable_index_max: Int = 0
150
151 # Association between nit variable and the corrsponding c variable index
152 var _varindexes: Map[Variable, Int] = new HashMap[Variable, Int]
153
154 # Are we currenlty in a closure definition?
155 readable writable var _closure: nullable NitMethodContext = null
156
157 # Return the cvariable of a Nit variable
158 fun 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 fun get_var(comment: nullable 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 fun 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 var _closurevariable_index: Int = 0
190
191 fun 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 fun 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 fun 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 fun 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 fun 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 fun 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 var _method: nullable MMSrcMethod
276
277 # Association between parameters and the corresponding variables
278 readable writable var _method_params: nullable Array[ParamVariable]
279
280 # Where a nit return must branch
281 readable writable var _return_label: nullable String
282
283 # Where a nit break must branch
284 readable writable var _break_label: nullable String
285
286 # Where a nit continue must branch
287 readable writable var _continue_label: nullable String
288
289 # Variable where a functionnal nit return must store its value
290 readable writable var _return_value: nullable String
291
292 # Variable where a functionnal nit break must store its value
293 readable writable var _break_value: nullable String
294
295 # Variable where a functionnal nit continue must store its value
296 readable writable var _continue_value: nullable String
297
298 init(method: nullable MMSrcMethod)
299 do
300 _method = method
301 end
302 end
303
304 ###############################################################################
305
306 redef class ClosureVariable
307 readable writable var _ctypename: nullable String
308 end
309
310 redef class MMMethod
311 # Compile as an expression.
312 # require that signature.return_type != null
313 fun 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 fun 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 fun intern_compile_call(v: CompilerVisitor, cargs: Array[String]): nullable 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 fun compile_call_and_closures(v: CompilerVisitor, cargs: Array[String], clos_defs: nullable Array[PClosureDef]): nullable String
377 do
378 var ve: String
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 fun 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 fun 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 fun 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 fun compile_isset(v: CompilerVisitor, n: PNode, recv: String): String
459 do
460 return "TAG_Bool({global.attr_access}({recv})!=NIT_NULL) /* isset {local_class}::{name}*/"
461 end
462
463 # Compile a read acces on selffor a given reciever.
464 fun compile_read_access(v: CompilerVisitor, n: PNode, recv: String): String
465 do
466 var res = "{global.attr_access}({recv}) /*{local_class}::{name}*/"
467 if not signature.return_type.is_nullable then
468 res = v.ensure_var(res, "{local_class}::{name}")
469 v.add_instr("if ({res} == NIT_NULL) \{ fprintf(stderr, \"Uninitialized attribute %s\", \"{name}\"); {v.printf_locate_error(n)} nit_exit(1); } /* implicit isset */;")
470 end
471 return res
472 end
473
474 # Compile a write acces on selffor a given reciever.
475 fun compile_write_access(v: CompilerVisitor, n: nullable PNode, recv: String, value: String)
476 do
477 v.add_instr("{global.attr_access}({recv}) /*{local_class}::{name}*/ = {value};")
478 end
479 end
480
481 redef class MMLocalProperty
482 # Compile the property as a C property
483 fun compile_property_to_c(v: CompilerVisitor) do end
484 end
485
486 redef class MMSrcMethod
487
488 # Compile and declare the signature to C
489 protected fun decl_csignature(v: CompilerVisitor, args: Array[String]): String
490 do
491 var params = new Array[String]
492 params.add("val_t {args[0]}")
493 for i in [0..signature.arity[ do
494 var p = "val_t {args[i+1]}"
495 params.add(p)
496 end
497
498 var first_closure_index = signature.arity + 1 # Wich parameter is the first closure
499 for i in [0..signature.closures.length[ do
500 var closcn = closure_cname(i)
501 var cs = signature.closures[i].signature # Closure signature
502 var subparams = new Array[String] # Parameters of the closure
503 subparams.add("struct WBT_ *")
504 for j in [0..cs.arity[ do
505 var p = "val_t"
506 subparams.add(p)
507 end
508 var r = "void"
509 if cs.return_type != null then r = "val_t"
510 params.add("struct WBT_ *{args[first_closure_index+i]}")
511 v.add_decl("typedef {r} (*{closcn})({subparams.join(", ")});")
512 end
513
514 if global.is_init then
515 params.add("int* init_table")
516 end
517
518 var ret: String
519 if signature.return_type != null then
520 ret = "val_t"
521 else
522 ret = "void"
523 end
524
525 var p = params.join(", ")
526 var s = "{ret} {cname}({p})"
527 v.add_decl("typedef {ret} (* {cname}_t)({p});")
528 v.add_decl(s + ";")
529 return s
530 end
531
532 redef fun compile_property_to_c(v)
533 do
534 v.cfc = new CFunctionContext(v)
535
536 var args = new Array[String]
537 args.add(" self")
538 for i in [0..signature.arity[ do
539 args.add(" param{i}")
540 end
541 for i in [0..signature.closures.length[ do
542 args.add(" wd{i}")
543 end
544 var cs = decl_csignature(v, args)
545 v.add_decl("#define LOCATE_{cname} \"{full_name}\"")
546
547 v.add_instr("{cs} \{")
548 v.indent
549 var ctx_old = v.ctx
550 v.ctx = new CContext
551
552 v.out_contexts.clear
553
554 var ln = 0
555 var s = self
556 if s.node != null then ln = s.node.line_number
557 v.add_decl("struct trace_t trace = \{NULL, NULL, {ln}, LOCATE_{cname}};")
558 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
559 v.add_instr("trace.file = LOCATE_{module.name};")
560 var s = do_compile_inside(v, args)
561 v.add_instr("tracehead = trace.prev;")
562 if s == null then
563 v.add_instr("return;")
564 else
565 v.add_instr("return {s};")
566 end
567
568 v.cfc.generate_var_decls
569
570 ctx_old.append(v.ctx)
571 v.ctx = ctx_old
572 v.unindent
573 v.add_instr("}")
574
575 for ctx in v.out_contexts do v.ctx.merge(ctx)
576 end
577
578 # Compile the method body inline
579 fun do_compile_inside(v: CompilerVisitor, params: Array[String]): nullable String is abstract
580 end
581
582 redef class MMReadImplementationMethod
583 redef fun do_compile_inside(v, params)
584 do
585 return node.prop.compile_read_access(v, node, params[0])
586 end
587 end
588
589 redef class MMWriteImplementationMethod
590 redef fun do_compile_inside(v, params)
591 do
592 node.prop.compile_write_access(v, node, params[0], params[1])
593 return null
594 end
595 end
596
597 redef class MMMethSrcMethod
598 redef fun do_compile_inside(v, params)
599 do
600 return node.do_compile_inside(v, self, params)
601 end
602 end
603
604 redef class MMImplicitInit
605 redef fun do_compile_inside(v, params)
606 do
607 var f = params.length - unassigned_attributes.length
608 var recv = params.first
609 for sp in super_inits do
610 assert sp isa MMMethod
611 var args_recv = [recv]
612 if sp == super_init then
613 var args = new Array[String].with_capacity(f)
614 args.add(recv)
615 for i in [1..f[ do
616 args.add(params[i])
617 end
618 sp.compile_stmt_call(v, args)
619 else
620 sp.compile_stmt_call(v, args_recv)
621 end
622 end
623 for i in [f..params.length[ do
624 var attribute = unassigned_attributes[i-f]
625 attribute.compile_write_access(v, null, recv, params[i])
626 end
627 return null
628 end
629 end
630
631 redef class MMType
632 # Compile a subtype check to self
633 # Return a NIT Bool
634 fun compile_cast(v: CompilerVisitor, recv: String, fromtype: MMType): String
635 do
636 # Fixme: handle formaltypes
637 var g = local_class.global
638 var s = ""
639 if fromtype.is_nullable then
640 if self.is_nullable then
641 s = "({recv}==NIT_NULL) || "
642 else
643 s = "({recv}!=NIT_NULL) && "
644 end
645 else
646 # FIXME This is used to not break code without the nullable KW
647 s = "({recv}==NIT_NULL) || "
648 end
649 return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
650 end
651
652 # Compile a cast assertion
653 fun compile_type_check(v: CompilerVisitor, recv: String, n: PNode, fromtype: MMType)
654 do
655 # Fixme: handle formaltypes
656 var g = local_class.global
657 var s = ""
658 if fromtype.is_nullable then
659 if self.is_nullable then
660 s = "({recv}!=NIT_NULL) && "
661 else
662 s = "({recv}==NIT_NULL) || "
663 end
664 else
665 # FIXME This is used to not break code without the nullable KW
666 s = "({recv}!=NIT_NULL) && "
667 end
668 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}*/;")
669 end
670
671 # Compile a notnull cast assertion
672 fun compile_notnull_check(v: CompilerVisitor, recv: String, n: PNode)
673 do
674 if is_nullable then
675 v.add_instr("if (({recv}==NIT_NULL)) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
676 end
677 end
678 end
679
680 ###############################################################################
681
682 redef class AMethPropdef
683 # Compile the method body
684 fun do_compile_inside(v: CompilerVisitor, method: MMSrcMethod, params: Array[String]): nullable String is abstract
685 end
686
687 redef class PSignature
688 fun compile_parameters(v: CompilerVisitor, orig_sig: MMSignature, params: Array[String]) is abstract
689 end
690
691 redef class ASignature
692 redef fun compile_parameters(v: CompilerVisitor, orig_sig: MMSignature, params: Array[String])
693 do
694 for ap in n_params do
695 var cname = v.cfc.register_variable(ap.variable)
696 v.nmc.method_params.add(ap.variable)
697 var orig_type = orig_sig[ap.position]
698 if not orig_type < ap.variable.stype.as(not null) then
699 # FIXME: do not test always
700 # FIXME: handle formal types
701 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
702 ap.variable.stype.compile_type_check(v, params[ap.position], ap, orig_type)
703 end
704 v.add_assignment(cname, params[ap.position])
705 end
706 for i in [0..n_closure_decls.length[ do
707 var wd = n_closure_decls[i]
708 var cname = v.cfc.register_closurevariable(wd.variable)
709 wd.variable.ctypename = v.nmc.method.closure_cname(i)
710 v.add_assignment(cname, "{params[orig_sig.arity + i]}")
711 end
712 end
713 end
714
715 redef class AConcreteMethPropdef
716 redef fun do_compile_inside(v, method, params)
717 do
718 var old_nmc = v.nmc
719 v.nmc = new NitMethodContext(method)
720
721 var selfcname = v.cfc.register_variable(self_var)
722 v.add_assignment(selfcname, params[0])
723 params.shift
724 v.nmc.method_params = [self_var]
725
726 var orig_meth: MMLocalProperty = method.global.intro
727 var orig_sig = orig_meth.signature_for(method.signature.recv)
728 if n_signature != null then
729 n_signature.compile_parameters(v, orig_sig, params)
730 end
731
732 var itpos: nullable String = null
733 if self isa AConcreteInitPropdef then
734 itpos = "VAL2OBJ({selfcname})->vft[{method.local_class.global.init_table_pos_id}].i"
735 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
736 v.add_instr("if (init_table[{itpos}]) return;")
737 end
738
739 v.nmc.return_label = "return_label{v.new_number}"
740 v.nmc.return_value = v.cfc.get_var("Method return value and escape marker")
741 if self isa AConcreteInitPropdef then
742 v.invoke_super_init_calls_after(null)
743 end
744 v.compile_stmt(n_block)
745 v.add_instr("{v.nmc.return_label}: while(false);")
746 if self isa AConcreteInitPropdef then
747 v.add_instr("init_table[{itpos}] = 1;")
748 end
749
750 var ret: nullable String = null
751 if method.signature.return_type != null then
752 ret = v.nmc.return_value
753 end
754
755 v.nmc = old_nmc
756 return ret
757 end
758 end
759
760 redef class ADeferredMethPropdef
761 redef fun do_compile_inside(v, method, params)
762 do
763 v.add_instr("fprintf(stderr, \"Deferred method called\");")
764 v.add_instr(v.printf_locate_error(self))
765 v.add_instr("nit_exit(1);")
766 if method.signature.return_type != null then
767 return("NIT_NULL")
768 else
769 return null
770 end
771 end
772 end
773
774 redef class AExternMethPropdef
775 redef fun do_compile_inside(v, method, params)
776 do
777 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
778 if n_extern != null then
779 ename = n_extern.text
780 ename = ename.substring(1, ename.length-2)
781 end
782 var sig = method.signature
783 if params.length != sig.arity + 1 then
784 printl("par:{params.length} sig:{sig.arity}")
785 end
786 var args = new Array[String]
787 args.add(sig.recv.unboxtype(params[0]))
788 for i in [0..sig.arity[ do
789 args.add(sig[i].unboxtype(params[i+1]))
790 end
791 var s = "{ename}({args.join(", ")})"
792 if sig.return_type != null then
793 return sig.return_type.boxtype(s)
794 else
795 v.add_instr("{s};")
796 return null
797 end
798 end
799 end
800
801 redef class AInternMethPropdef
802 redef fun do_compile_inside(v, method, p)
803 do
804 var c = method.local_class.name
805 var n = method.name
806 var s: nullable String = null
807 if c == once "Int".to_symbol then
808 if n == once "object_id".to_symbol then
809 s = "{p[0]}"
810 else if n == once "unary -".to_symbol then
811 s = "TAG_Int(-UNTAG_Int({p[0]}))"
812 else if n == once "output".to_symbol then
813 v.add_instr("printf(\"%ld\\n\", UNTAG_Int({p[0]}));")
814 else if n == once "ascii".to_symbol then
815 s = "TAG_Char(UNTAG_Int({p[0]}))"
816 else if n == once "succ".to_symbol then
817 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
818 else if n == once "prec".to_symbol then
819 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
820 else if n == once "to_f".to_symbol then
821 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
822 else if n == once "+".to_symbol then
823 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
824 else if n == once "-".to_symbol then
825 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
826 else if n == once "*".to_symbol then
827 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
828 else if n == once "/".to_symbol then
829 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
830 else if n == once "%".to_symbol then
831 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
832 else if n == once "<".to_symbol then
833 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
834 else if n == once ">".to_symbol then
835 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
836 else if n == once "<=".to_symbol then
837 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
838 else if n == once ">=".to_symbol then
839 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
840 else if n == once "lshift".to_symbol then
841 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
842 else if n == once "rshift".to_symbol then
843 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
844 else if n == once "==".to_symbol then
845 s = "TAG_Bool(({p[0]})==({p[1]}))"
846 else if n == once "!=".to_symbol then
847 s = "TAG_Bool(({p[0]})!=({p[1]}))"
848 end
849 else if c == once "Float".to_symbol then
850 if n == once "object_id".to_symbol then
851 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
852 else if n == once "unary -".to_symbol then
853 s = "BOX_Float(-UNBOX_Float({p[0]}))"
854 else if n == once "output".to_symbol then
855 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
856 else if n == once "to_i".to_symbol then
857 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
858 else if n == once "+".to_symbol then
859 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
860 else if n == once "-".to_symbol then
861 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
862 else if n == once "*".to_symbol then
863 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
864 else if n == once "/".to_symbol then
865 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
866 else if n == once "<".to_symbol then
867 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
868 else if n == once ">".to_symbol then
869 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
870 else if n == once "<=".to_symbol then
871 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
872 else if n == once ">=".to_symbol then
873 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
874 end
875 else if c == once "Char".to_symbol then
876 if n == once "object_id".to_symbol then
877 s = "TAG_Int(UNTAG_Char({p[0]}))"
878 else if n == once "unary -".to_symbol then
879 s = "TAG_Char(-UNTAG_Char({p[0]}))"
880 else if n == once "output".to_symbol then
881 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
882 else if n == once "ascii".to_symbol then
883 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
884 else if n == once "succ".to_symbol then
885 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
886 else if n == once "prec".to_symbol then
887 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
888 else if n == once "to_i".to_symbol then
889 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
890 else if n == once "+".to_symbol then
891 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
892 else if n == once "-".to_symbol then
893 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
894 else if n == once "*".to_symbol then
895 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
896 else if n == once "/".to_symbol then
897 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
898 else if n == once "%".to_symbol then
899 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
900 else if n == once "<".to_symbol then
901 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
902 else if n == once ">".to_symbol then
903 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
904 else if n == once "<=".to_symbol then
905 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
906 else if n == once ">=".to_symbol then
907 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
908 else if n == once "==".to_symbol then
909 s = "TAG_Bool(({p[0]})==({p[1]}))"
910 else if n == once "!=".to_symbol then
911 s = "TAG_Bool(({p[0]})!=({p[1]}))"
912 end
913 else if c == once "Bool".to_symbol then
914 if n == once "object_id".to_symbol then
915 s = "TAG_Int(UNTAG_Bool({p[0]}))"
916 else if n == once "unary -".to_symbol then
917 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
918 else if n == once "output".to_symbol then
919 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
920 else if n == once "ascii".to_symbol then
921 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
922 else if n == once "to_i".to_symbol then
923 s = "TAG_Int(UNTAG_Bool({p[0]}))"
924 else if n == once "==".to_symbol then
925 s = "TAG_Bool(({p[0]})==({p[1]}))"
926 else if n == once "!=".to_symbol then
927 s = "TAG_Bool(({p[0]})!=({p[1]}))"
928 end
929 else if c == once "NativeArray".to_symbol then
930 if n == once "object_id".to_symbol then
931 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
932 else if n == once "[]".to_symbol then
933 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
934 else if n == once "[]=".to_symbol then
935 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
936 else if n == once "copy_to".to_symbol then
937 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
938 end
939 else if c == once "NativeString".to_symbol then
940 if n == once "object_id".to_symbol then
941 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
942 else if n == once "atoi".to_symbol then
943 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
944 else if n == once "[]".to_symbol then
945 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
946 else if n == once "[]=".to_symbol then
947 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
948 else if n == once "copy_to".to_symbol then
949 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]}));")
950 end
951 else if n == once "object_id".to_symbol then
952 s = "TAG_Int((bigint){p[0]})"
953 else if n == once "sys".to_symbol then
954 s = "(G_sys)"
955 else if n == once "is_same_type".to_symbol then
956 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
957 else if n == once "exit".to_symbol then
958 v.add_instr("exit(UNTAG_Int({p[1]}));")
959 else if n == once "calloc_array".to_symbol then
960 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
961 else if n == once "calloc_string".to_symbol then
962 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
963
964 else
965 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
966 end
967 if method.signature.return_type != null and s == null then
968 s = "NIT_NULL /*stub*/"
969 end
970 return s
971 end
972 end
973
974 ###############################################################################
975
976 redef class PExpr
977 # Compile the node as an expression
978 # Only the visitor should call it
979 fun compile_expr(v: CompilerVisitor): String is abstract
980
981 # Prepare a call of node as a statement
982 # Only the visitor should call it
983 # It's used for local variable managment
984 fun prepare_compile_stmt(v: CompilerVisitor) do end
985
986 # Compile the node as a statement
987 # Only the visitor should call it
988 fun compile_stmt(v: CompilerVisitor) do printl("Error!")
989 end
990
991 redef class ABlockExpr
992 redef fun compile_stmt(v)
993 do
994 for n in n_expr do
995 v.compile_stmt(n)
996 end
997 end
998 end
999
1000 redef class AVardeclExpr
1001 redef fun prepare_compile_stmt(v)
1002 do
1003 v.cfc.register_variable(variable)
1004 end
1005
1006 redef fun compile_stmt(v)
1007 do
1008 var cname = v.cfc.varname(variable)
1009 if n_expr == null then
1010 v.add_instr("/*{cname} is variable {variable.name}*/")
1011 else
1012 var e = v.compile_expr(n_expr.as(not null))
1013 v.add_assignment(cname, e)
1014 end
1015 end
1016 end
1017
1018 redef class AReturnExpr
1019 redef fun compile_stmt(v)
1020 do
1021 if n_expr != null then
1022 var e = v.compile_expr(n_expr.as(not null))
1023 v.add_assignment(v.nmc.return_value.as(not null), e)
1024 end
1025 if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.return_value});")
1026 v.add_instr("goto {v.nmc.return_label};")
1027 end
1028 end
1029
1030 redef class ABreakExpr
1031 redef fun compile_stmt(v)
1032 do
1033 if n_expr != null then
1034 var e = v.compile_expr(n_expr.as(not null))
1035 v.add_assignment(v.nmc.break_value.as(not null), e)
1036 end
1037 if v.cfc.closure == v.nmc then v.add_instr("closctx->has_broke = &({v.nmc.break_value}); closctx->broke_value = *closctx->has_broke;")
1038 v.add_instr("goto {v.nmc.break_label};")
1039 end
1040 end
1041
1042 redef class AContinueExpr
1043 redef fun compile_stmt(v)
1044 do
1045 if n_expr != null then
1046 var e = v.compile_expr(n_expr.as(not null))
1047 v.add_assignment(v.nmc.continue_value.as(not null), e)
1048 end
1049 v.add_instr("goto {v.nmc.continue_label};")
1050 end
1051 end
1052
1053 redef class AAbortExpr
1054 redef fun compile_stmt(v)
1055 do
1056 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
1057 end
1058 end
1059
1060 redef class ADoExpr
1061 redef fun compile_stmt(v)
1062 do
1063 v.compile_stmt(n_block)
1064 end
1065 end
1066
1067 redef class AIfExpr
1068 redef fun compile_stmt(v)
1069 do
1070 var e = v.compile_expr(n_expr)
1071 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
1072 v.cfc.free_var(e)
1073 if n_then != null then
1074 v.indent
1075 v.compile_stmt(n_then)
1076 v.unindent
1077 end
1078 if n_else != null then
1079 v.add_instr("} else \{ /*if*/")
1080 v.indent
1081 v.compile_stmt(n_else)
1082 v.unindent
1083 end
1084 v.add_instr("}")
1085 end
1086 end
1087
1088 redef class AIfexprExpr
1089 redef fun compile_expr(v)
1090 do
1091 var e = v.compile_expr(n_expr)
1092 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
1093 v.cfc.free_var(e)
1094 v.indent
1095 var e = v.ensure_var(v.compile_expr(n_then), "Then value")
1096 v.unindent
1097 v.add_instr("} else \{ /*if*/")
1098 v.cfc.free_var(e)
1099 v.indent
1100 var e2 = v.ensure_var(v.compile_expr(n_else), "Else value")
1101 v.add_assignment(e, e2)
1102 v.unindent
1103 v.add_instr("}")
1104 return e
1105 end
1106 end
1107
1108 class AControlableBlock
1109 special PExpr
1110 fun compile_inside_block(v: CompilerVisitor) is abstract
1111 redef fun compile_stmt(v)
1112 do
1113 var old_break_label = v.nmc.break_label
1114 var old_continue_label = v.nmc.continue_label
1115 var id = v.new_number
1116 v.nmc.break_label = "break_{id}"
1117 v.nmc.continue_label = "continue_{id}"
1118
1119 compile_inside_block(v)
1120
1121
1122 v.nmc.break_label = old_break_label
1123 v.nmc.continue_label = old_continue_label
1124 end
1125 end
1126
1127 redef class AWhileExpr
1128 special AControlableBlock
1129 redef fun compile_inside_block(v)
1130 do
1131 v.add_instr("while (true) \{ /*while*/")
1132 v.indent
1133 var e = v.compile_expr(n_expr)
1134 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
1135 v.cfc.free_var(e)
1136 v.compile_stmt(n_block)
1137 v.add_instr("{v.nmc.continue_label}: while(0);")
1138 v.unindent
1139 v.add_instr("}")
1140 v.add_instr("{v.nmc.break_label}: while(0);")
1141 end
1142 end
1143
1144 redef class AForExpr
1145 special AControlableBlock
1146 redef fun compile_inside_block(v)
1147 do
1148 var e = v.compile_expr(n_expr)
1149 var ittype = meth_iterator.signature.return_type
1150 v.cfc.free_var(e)
1151 var iter = v.cfc.get_var("For iterator")
1152 v.add_assignment(iter, meth_iterator.compile_expr_call(v, [e]))
1153 v.add_instr("while (true) \{ /*for*/")
1154 v.indent
1155 var ok = v.cfc.get_var("For 'is_ok' result")
1156 v.add_assignment(ok, meth_is_ok.compile_expr_call(v, [iter]))
1157 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
1158 v.cfc.free_var(ok)
1159 var e = meth_item.compile_expr_call(v, [iter])
1160 e = v.ensure_var(e, "For item")
1161 var cname = v.cfc.register_variable(variable)
1162 v.add_assignment(cname, e)
1163 v.compile_stmt(n_block)
1164 v.add_instr("{v.nmc.continue_label}: while(0);")
1165 meth_next.compile_stmt_call(v, [iter])
1166 v.unindent
1167 v.add_instr("}")
1168 v.add_instr("{v.nmc.break_label}: while(0);")
1169 end
1170 end
1171
1172 redef class AAssertExpr
1173 redef fun compile_stmt(v)
1174 do
1175 var e = v.compile_expr(n_expr)
1176 var s = ""
1177 if n_id != null then
1178 s = " '{n_id.text}' "
1179 end
1180 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
1181 end
1182 end
1183
1184 redef class AVarExpr
1185 redef fun compile_expr(v)
1186 do
1187 return " {v.cfc.varname(variable)} /*{variable.name}*/"
1188 end
1189 end
1190
1191 redef class AVarAssignExpr
1192 redef fun compile_stmt(v)
1193 do
1194 var e = v.compile_expr(n_value)
1195 v.add_assignment(v.cfc.varname(variable), "{e} /*{variable.name}=*/")
1196 end
1197 end
1198
1199 redef class AVarReassignExpr
1200 redef fun compile_stmt(v)
1201 do
1202 var e1 = v.cfc.varname(variable)
1203 var e2 = v.compile_expr(n_value)
1204 var e3 = assign_method.compile_expr_call(v, [e1, e2])
1205 v.add_assignment(v.cfc.varname(variable), "{e3} /*{variable.name}*/")
1206 end
1207 end
1208
1209 redef class ASelfExpr
1210 redef fun compile_expr(v)
1211 do
1212 return v.cfc.varname(v.nmc.method_params[0])
1213 end
1214 end
1215
1216 redef class AOrExpr
1217 redef fun compile_expr(v)
1218 do
1219 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'or' operand")
1220 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
1221 v.cfc.free_var(e)
1222 v.indent
1223 var e2 = v.compile_expr(n_expr2)
1224 v.add_assignment(e, e2)
1225 v.unindent
1226 v.add_instr("}")
1227 return e
1228 end
1229 end
1230
1231 redef class AAndExpr
1232 redef fun compile_expr(v)
1233 do
1234 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'and' operand")
1235 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
1236 v.cfc.free_var(e)
1237 v.indent
1238 var e2 = v.compile_expr(n_expr2)
1239 v.add_assignment(e, e2)
1240 v.unindent
1241 v.add_instr("}")
1242 return e
1243 end
1244 end
1245
1246 redef class ANotExpr
1247 redef fun compile_expr(v)
1248 do
1249 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1250 end
1251 end
1252
1253 redef class AEeExpr
1254 redef fun compile_expr(v)
1255 do
1256 var e = v.compile_expr(n_expr)
1257 var e2 = v.compile_expr(n_expr2)
1258 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
1259 end
1260 end
1261
1262 redef class AIsaExpr
1263 redef fun compile_expr(v)
1264 do
1265 var e = v.compile_expr(n_expr)
1266 return n_type.stype.compile_cast(v, e, n_expr.stype)
1267 end
1268 end
1269
1270 redef class AAsCastExpr
1271 redef fun compile_expr(v)
1272 do
1273 var e = v.compile_expr(n_expr)
1274 n_type.stype.compile_type_check(v, e, self, n_expr.stype)
1275 return e
1276 end
1277 end
1278
1279 redef class AAsNotnullExpr
1280 redef fun compile_expr(v)
1281 do
1282 var e = v.compile_expr(n_expr)
1283 n_expr.stype.compile_notnull_check(v, e, self)
1284 return e
1285 end
1286 end
1287
1288 redef class ATrueExpr
1289 redef fun compile_expr(v)
1290 do
1291 return " TAG_Bool(true)"
1292 end
1293 end
1294
1295 redef class AFalseExpr
1296 redef fun compile_expr(v)
1297 do
1298 return " TAG_Bool(false)"
1299 end
1300 end
1301
1302 redef class AIntExpr
1303 redef fun compile_expr(v)
1304 do
1305 return " TAG_Int({n_number.text})"
1306 end
1307 end
1308
1309 redef class AFloatExpr
1310 redef fun compile_expr(v)
1311 do
1312 return "BOX_Float({n_float.text})"
1313 end
1314 end
1315
1316 redef class ACharExpr
1317 redef fun compile_expr(v)
1318 do
1319 return " TAG_Char({n_char.text})"
1320 end
1321 end
1322
1323 redef class AStringFormExpr
1324 redef fun compile_expr(v)
1325 do
1326 compute_string_info
1327 var i = v.new_number
1328 var cvar = v.cfc.get_var("Once String constant")
1329 v.add_decl("static val_t once_value_{i} = NIT_NULL; /* Once value for string {cvar}*/")
1330 v.add_instr("if (once_value_{i} != NIT_NULL) {cvar} = once_value_{i};")
1331 v.add_instr("else \{")
1332 v.indent
1333 v.cfc.free_var(cvar)
1334 var e = meth_with_native.compile_constructor_call(v, stype, ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1335 v.add_assignment(cvar, e)
1336 v.add_instr("once_value_{i} = {cvar};")
1337 v.unindent
1338 v.add_instr("}")
1339 return cvar
1340 end
1341
1342 # The raw string value
1343 protected fun string_text: String is abstract
1344
1345 # The string in a C native format
1346 protected var _cstring: nullable String
1347
1348 # The string length in bytes
1349 protected var _cstring_length: nullable Int
1350
1351 # Compute _cstring and _cstring_length using string_text
1352 protected fun compute_string_info
1353 do
1354 var len = 0
1355 var str = string_text
1356 var res = new Buffer
1357 var i = 0
1358 while i < str.length do
1359 var c = str[i]
1360 if c == '\\' then
1361 i = i + 1
1362 var c2 = str[i]
1363 if c2 != '{' and c2 != '}' then
1364 res.add(c)
1365 end
1366 c = c2
1367 end
1368 len = len + 1
1369 res.add(c)
1370 i = i + 1
1371 end
1372 _cstring = res.to_s
1373 _cstring_length = len
1374 end
1375 end
1376
1377 redef class AStringExpr
1378 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1379 end
1380 redef class AStartStringExpr
1381 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1382 end
1383 redef class AMidStringExpr
1384 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1385 end
1386 redef class AEndStringExpr
1387 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1388 end
1389
1390 redef class ASuperstringExpr
1391 redef fun compile_expr(v)
1392 do
1393 var array = meth_with_capacity.compile_constructor_call(v, atype.as(not null), ["TAG_Int({n_exprs.length})"])
1394 array = v.ensure_var(array, "Array (for super-string)")
1395
1396 for ne in n_exprs do
1397 var e = v.ensure_var(v.compile_expr(ne), "super-string element")
1398 if ne.stype != stype then
1399 v.cfc.free_var(e)
1400 e = meth_to_s.compile_expr_call(v, [e])
1401 end
1402 v.cfc.free_var(e)
1403 meth_add.compile_stmt_call(v, [array, e])
1404 end
1405
1406 return meth_to_s.compile_expr_call(v, [array])
1407 end
1408 end
1409
1410 redef class ANullExpr
1411 redef fun compile_expr(v)
1412 do
1413 return " NIT_NULL /*null*/"
1414 end
1415 end
1416
1417 redef class AArrayExpr
1418 redef fun compile_expr(v)
1419 do
1420 var recv = meth_with_capacity.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1421 recv = v.ensure_var(recv, "Literal array")
1422
1423 for ne in n_exprs do
1424 var e = v.compile_expr(ne)
1425 meth_add.compile_stmt_call(v, [recv, e])
1426 end
1427 return recv
1428 end
1429 end
1430
1431 redef class ARangeExpr
1432 redef fun compile_expr(v)
1433 do
1434 var e = v.compile_expr(n_expr)
1435 var e2 = v.compile_expr(n_expr2)
1436 return meth_init.compile_constructor_call(v, stype, [e, e2])
1437 end
1438 end
1439
1440 redef class ASuperExpr
1441 redef fun compile_stmt(v)
1442 do
1443 var e = intern_compile_call(v)
1444 if e != null then
1445 v.add_instr(e + ";")
1446 end
1447 end
1448
1449 redef fun compile_expr(v)
1450 do
1451 var e = intern_compile_call(v)
1452 assert e != null
1453 return e
1454 end
1455
1456 private fun intern_compile_call(v: CompilerVisitor): nullable String
1457 do
1458 var arity = v.nmc.method_params.length - 1
1459 if init_in_superclass != null then
1460 arity = init_in_superclass.signature.arity
1461 end
1462 var args = new Array[String].with_capacity(arity + 1)
1463 args.add(v.cfc.varname(v.nmc.method_params[0]))
1464 if n_args.length != arity then
1465 for i in [0..arity[ do
1466 args.add(v.cfc.varname(v.nmc.method_params[i + 1]))
1467 end
1468 else
1469 for na in n_args do
1470 args.add(v.compile_expr(na))
1471 end
1472 end
1473 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1474 if init_in_superclass != null then
1475 return init_in_superclass.intern_compile_call(v, args)
1476 else
1477 if prop.global.is_init then args.add("init_table")
1478 return prop.compile_super_call(v, args)
1479 end
1480 end
1481 end
1482
1483 redef class AAttrExpr
1484 redef fun compile_expr(v)
1485 do
1486 var e = v.compile_expr(n_expr)
1487 return prop.compile_read_access(v, n_id, e)
1488 end
1489 end
1490
1491 redef class AAttrAssignExpr
1492 redef fun compile_stmt(v)
1493 do
1494 var e = v.compile_expr(n_expr)
1495 var e2 = v.compile_expr(n_value)
1496 prop.compile_write_access(v, n_id, e, e2)
1497 end
1498 end
1499 redef class AAttrReassignExpr
1500 redef fun compile_stmt(v)
1501 do
1502 var e1 = v.compile_expr(n_expr)
1503 var e2 = prop.compile_read_access(v, n_id, e1)
1504 var e3 = v.compile_expr(n_value)
1505 var e4 = assign_method.compile_expr_call(v, [e2, e3])
1506 prop.compile_write_access(v, n_id, e1, e4)
1507 end
1508 end
1509
1510 redef class AIssetAttrExpr
1511 redef fun compile_expr(v)
1512 do
1513 var e = v.compile_expr(n_expr)
1514 return prop.compile_isset(v, n_id, e)
1515 end
1516 end
1517
1518 redef class AAbsAbsSendExpr
1519 # Compile each argument and add them to the array
1520 fun compile_arguments_in(v: CompilerVisitor, cargs: Array[String])
1521 do
1522 for a in arguments.as(not null) do
1523 cargs.add(v.compile_expr(a))
1524 end
1525 end
1526
1527 end
1528
1529 redef class ASendExpr
1530 private fun intern_compile_call(v: CompilerVisitor): nullable String
1531 do
1532 var recv = v.compile_expr(n_expr)
1533 var cargs = new Array[String]
1534 cargs.add(recv)
1535 compile_arguments_in(v, cargs)
1536
1537 var e: nullable String
1538 if prop_signature.closures.is_empty then
1539 e = prop.intern_compile_call(v, cargs)
1540 else
1541 e = prop.compile_call_and_closures(v, cargs, closure_defs)
1542 end
1543
1544 if prop.global.is_init then
1545 v.invoke_super_init_calls_after(prop)
1546 end
1547 return e
1548 end
1549
1550 redef fun compile_expr(v)
1551 do
1552 var e = intern_compile_call(v)
1553 assert e != null
1554 return e
1555 end
1556
1557 redef fun compile_stmt(v)
1558 do
1559 var e = intern_compile_call(v)
1560 if e != null then
1561 v.add_instr(e + ";")
1562 end
1563 end
1564 end
1565
1566 redef class ASendReassignExpr
1567 redef fun compile_expr(v) do abort
1568
1569 redef fun compile_stmt(v)
1570 do
1571 var recv = v.compile_expr(n_expr)
1572 var cargs = new Array[String]
1573 cargs.add(recv)
1574 compile_arguments_in(v, cargs)
1575
1576 var e2 = read_prop.compile_expr_call(v, cargs)
1577 var e3 = v.compile_expr(n_value)
1578 var e4 = assign_method.compile_expr_call(v, [e2, e3])
1579 cargs.add(e4)
1580 prop.compile_stmt_call(v, cargs)
1581 end
1582 end
1583
1584 redef class ANewExpr
1585 redef fun compile_expr(v)
1586 do
1587 var cargs = new Array[String]
1588 compile_arguments_in(v, cargs)
1589 return prop.compile_constructor_call(v, stype, cargs)
1590 end
1591
1592 redef fun compile_stmt(v) do abort
1593 end
1594
1595 redef class PClosureDef
1596 # Compile the closure definition as a function in v.out_contexts
1597 # Return the cname of the function
1598 fun compile_closure(v: CompilerVisitor, closcn: String): String is abstract
1599
1600 # Compile the closure definition inside the current C function.
1601 fun do_compile_inside(v: CompilerVisitor, params: nullable Array[String]): nullable String is abstract
1602 end
1603
1604 redef class AClosureDef
1605 # The cname of the function
1606 readable var _cname: nullable String
1607
1608 redef fun compile_closure(v, closcn)
1609 do
1610 var ctx_old = v.ctx
1611 v.ctx = new CContext
1612 v.out_contexts.add(v.ctx)
1613
1614 var cfc_old = v.cfc.closure
1615 v.cfc.closure = v.nmc
1616
1617 var old_rv = v.nmc.return_value
1618 var old_bv = v.nmc.break_value
1619 if cfc_old == null then
1620 v.nmc.return_value = "closctx->{old_rv}"
1621 v.nmc.break_value = "closctx->{old_bv}"
1622 end
1623
1624 var cname = "OC_{v.nmc.method.cname}_{v.out_contexts.length}"
1625 _cname = cname
1626 var args = new Array[String]
1627 for i in [0..closure.signature.arity[ do
1628 args.add(" param{i}")
1629 end
1630
1631 var cs = decl_csignature(v, args, closcn)
1632
1633 v.add_instr("{cs} \{")
1634 v.indent
1635 var ctx_old2 = v.ctx
1636 v.ctx = new CContext
1637
1638 v.add_decl("struct trace_t trace = \{NULL, NULL, {line_number}, LOCATE_{v.nmc.method.cname}};")
1639 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
1640
1641 v.add_instr("trace.file = LOCATE_{v.module.name};")
1642 var s = do_compile_inside(v, args)
1643
1644 v.add_instr("{v.nmc.return_label}:")
1645 v.add_instr("tracehead = trace.prev;")
1646 if s == null then
1647 v.add_instr("return;")
1648 else
1649 v.add_instr("return {s};")
1650 end
1651
1652 ctx_old2.append(v.ctx)
1653 v.ctx = ctx_old2
1654 v.unindent
1655 v.add_instr("}")
1656 v.ctx = ctx_old
1657
1658 v.cfc.closure = cfc_old
1659 v.nmc.return_value = old_rv
1660 v.nmc.break_value = old_bv
1661
1662 # Build closure
1663 var closcnv = "wbclos{v.new_number}"
1664 v.add_decl("struct WBT_ {closcnv};")
1665 v.add_instr("{closcnv}.fun = (fun_t){cname};")
1666 v.add_instr("{closcnv}.has_broke = NULL;")
1667 if cfc_old != null then
1668 v.add_instr("{closcnv}.variable = closctx->variable;")
1669 v.add_instr("{closcnv}.closurevariable = closctx->closurevariable;")
1670 else
1671 v.add_instr("{closcnv}.variable = variable;")
1672 v.add_instr("{closcnv}.closurevariable = closurevariable;")
1673 end
1674
1675 return "(&{closcnv})"
1676 end
1677
1678 protected fun decl_csignature(v: CompilerVisitor, args: Array[String], closcn: String): String
1679 do
1680 var params = new Array[String]
1681 params.add("struct WBT_ *closctx")
1682 for i in [0..closure.signature.arity[ do
1683 var p = "val_t {args[i]}"
1684 params.add(p)
1685 end
1686 var ret: String
1687 if closure.signature.return_type != null then
1688 ret = "val_t"
1689 else
1690 ret = "void"
1691 end
1692 var p = params.join(", ")
1693 var s = "{ret} {cname}({p})"
1694 v.add_decl("typedef {ret} (* {cname}_t)({p});")
1695 v.add_decl(s + ";")
1696 return s
1697 end
1698
1699 redef fun do_compile_inside(v, params)
1700 do
1701 for i in [0..variables.length[ do
1702 var vacname = v.cfc.register_variable(variables[i])
1703 v.add_assignment(vacname, params[i])
1704 end
1705
1706 var old_cv = v.nmc.continue_value
1707 var old_cl = v.nmc.continue_label
1708 var old_bl = v.nmc.break_label
1709
1710 v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
1711 v.nmc.continue_label = "continue_label{v.new_number}"
1712 v.nmc.break_label = v.nmc.return_label
1713
1714 v.compile_stmt(n_expr)
1715
1716 v.add_instr("{v.nmc.continue_label}: while(false);")
1717
1718 var ret: nullable String = null
1719 if closure.signature.return_type != null then ret = v.nmc.continue_value
1720
1721 v.nmc.continue_value = old_cv
1722 v.nmc.continue_label = old_cl
1723 v.nmc.break_label = old_bl
1724
1725 return ret
1726 end
1727 end
1728
1729 redef class PClosureDecl
1730 fun do_compile_inside(v: CompilerVisitor, params: Array[String]): nullable String is abstract
1731 end
1732 redef class AClosureDecl
1733 redef fun do_compile_inside(v, params)
1734 do
1735 n_signature.compile_parameters(v, variable.closure.signature, params)
1736
1737 var old_cv = v.nmc.continue_value
1738 var old_cl = v.nmc.continue_label
1739 var old_bl = v.nmc.break_label
1740
1741 v.nmc.continue_value = v.cfc.get_var("Continue value and escape marker")
1742 v.nmc.continue_label = "continue_label{v.new_number}"
1743 v.nmc.break_label = v.nmc.return_label
1744
1745 v.compile_stmt(n_expr)
1746
1747 v.add_instr("{v.nmc.continue_label}: while(false);")
1748
1749 var ret: nullable String = null
1750 if variable.closure.signature.return_type != null then ret = v.nmc.continue_value
1751
1752 v.nmc.continue_value = old_cv
1753 v.nmc.continue_label = old_cl
1754 v.nmc.break_label = old_bl
1755
1756 return ret
1757 end
1758 end
1759
1760 redef class AClosureCallExpr
1761 fun intern_compile_call(v: CompilerVisitor): nullable String
1762 do
1763 var cargs = new Array[String]
1764 compile_arguments_in(v, cargs)
1765 var va: nullable String = null
1766 if variable.closure.signature.return_type != null then va = v.cfc.get_var("Closure call result value")
1767
1768 if variable.closure.is_optional then
1769 v.add_instr("if({v.cfc.varname(variable)}==NULL) \{")
1770 v.indent
1771 var n = variable.decl
1772 assert n isa AClosureDecl
1773 var s = n.do_compile_inside(v, cargs)
1774 if s != null then v.add_assignment(va.as(not null), s)
1775 v.unindent
1776 v.add_instr("} else \{")
1777 v.indent
1778 end
1779
1780 var ivar = v.cfc.varname(variable)
1781 var cargs2 = [ivar]
1782 cargs2.append(cargs)
1783 var s = "(({variable.ctypename})({ivar}->fun))({cargs2.join(", ")}) /* Invoke closure {variable} */"
1784 if va != null then
1785 v.add_assignment(va, s)
1786 else
1787 v.add_instr("{s};")
1788 end
1789 v.add_instr("if ({ivar}->has_broke) \{")
1790 v.indent
1791 if n_closure_defs.length == 1 then do
1792 n_closure_defs.first.do_compile_inside(v, null)
1793 end
1794 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;\}")
1795 v.add_instr("goto {v.nmc.return_label};")
1796 v.unindent
1797 v.add_instr("\}")
1798
1799 if variable.closure.is_optional then
1800 v.unindent
1801 v.add_instr("\}")
1802 end
1803 return va
1804 end
1805
1806 redef fun compile_expr(v)
1807 do
1808 var e = intern_compile_call(v)
1809 assert e != null
1810 return e
1811 end
1812
1813 redef fun compile_stmt(v)
1814 do
1815 var e = intern_compile_call(v)
1816 if e != null then
1817 v.add_instr(e + ";")
1818 end
1819 end
1820 end
1821
1822 redef class AProxyExpr
1823 redef fun compile_expr(v)
1824 do
1825 return v.compile_expr(n_expr)
1826 end
1827 end
1828
1829 redef class AOnceExpr
1830 redef fun compile_expr(v)
1831 do
1832 var i = v.new_number
1833 var cvar = v.cfc.get_var("Once expression result")
1834 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value for {cvar}*/")
1835 v.add_instr("if (once_bool_{i}) {cvar} = once_value_{i};")
1836 v.add_instr("else \{")
1837 v.indent
1838 v.cfc.free_var(cvar)
1839 var e = v.compile_expr(n_expr)
1840 v.add_assignment(cvar, e)
1841 v.add_instr("once_value_{i} = {cvar};")
1842 v.add_instr("once_bool_{i} = true;")
1843 v.unindent
1844 v.add_instr("}")
1845 return cvar
1846 end
1847 end