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