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