1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2008 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Compile method bodies, statments and expressions to C.
18 package compiling_methods
23 redef class CompilerVisitor
24 # Compile a statment node
25 fun compile_stmt
(n
: nullable PExpr)
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
32 cfc
._variable_index
= i
35 # Compile is expression node
36 fun compile_expr
(n
: PExpr): String
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
45 var v
= cfc
.get_var
("Result")
50 # Ensure that a c expression is a var
51 fun ensure_var
(s
: String, comment
: String): String
53 if cfc
.is_valid_variable
(s
) then
54 add_instr
("/* Ensure var {s}: {comment}*/")
57 var v
= cfc
.get_var
(null)
58 add_assignment
(v
, "{s} /* Ensure var: {comment}*/")
62 readable writable var _cfc
: nullable CFunctionContext
64 readable writable var _nmc
: nullable NitMethodContext
66 # Generate an fprintf to display an error location
67 fun printf_locate_error
(node
: PNode): String
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});")
77 fun invoke_super_init_calls_after
(start_prop
: nullable MMMethod)
79 var n
= nmc
.method
.node
80 assert n
isa AConcreteInitPropdef
82 if n
.super_init_calls
.is_empty
then return
86 if start_prop
!= null then
87 while n
.super_init_calls
[i
] != start_prop
do
88 #s.append(" {n.super_init_calls[i]}")
92 #s.append(" {start_prop}")
94 while n
.explicit_super_init_calls
[j
] != start_prop
do
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
]
103 var l
= n
.super_init_calls
.length
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]))
112 for va
in nmc
.method_params
.as(not null) do
113 cargs
.add
(cfc
.varname
(va
))
117 p
.compile_stmt_call
(self, cargs
)
122 # s.append(" {n.super_init_calls[i]}")
125 #if stop_prop != null then s.append(" (stop at {stop_prop})")
126 #n.printl("implicit calls in {n.method}: {s}")
130 # A C function currently written
131 class CFunctionContext
132 readable var _visitor
: CompilerVisitor
134 # Next available variable number
135 var _variable_index
: Int = 0
137 # Total number of variable
138 var _variable_index_max
: Int = 0
140 # Association between nit variable and the corrsponding c variable index
141 var _varindexes
: Map[Variable, Int] = new HashMap[Variable, Int]
143 # Are we currenlty in a closure definition?
144 readable writable var _closure
: nullable NitMethodContext = null
146 # Return the cvariable of a Nit variable
147 fun varname
(v
: Variable): String
149 if v
isa ClosureVariable then
150 return closure_variable
(_varindexes
[v
])
152 return variable
(_varindexes
[v
])
156 # Return the next available variable
157 fun get_var
(comment
: nullable String): String
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
164 if comment
!= null then
165 visitor
.add_instr
("/* Register {v}: {comment} */")
170 fun register_variable
(v
: Variable): String
172 _varindexes
[v
] = _variable_index
173 var s
= get_var
("Local variable")
177 # Next available closure variable number
178 var _closurevariable_index
: Int = 0
180 fun register_closurevariable
(v
: ClosureVariable): String
182 var s
= "closurevariable[{_closurevariable_index}]"
183 _varindexes
[v
] = _closurevariable_index
184 _closurevariable_index
+= 1
185 if _closure
!= null then
186 return "(closctx->{s})"
192 # Return the ith cvariable
193 protected fun variable
(i
: Int): String
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}])"
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}]"
214 # Return the ith closurevariable
215 protected fun closure_variable
(i
: Int): String
217 if closure
!= null then
218 return "(closctx->closurevariable[{i}])"
220 return "closurevariable[{i}]"
224 # Is s a valid variable
225 protected fun is_valid_variable
(s
: String): Bool
227 for i
in [0.._variable_index
[ do
228 if s
== variable
(i
) then return true
233 # Mark the variable available
234 fun free_var
(v
: String)
237 if v
== variable
(_variable_index-1
) then
238 _variable_index
= _variable_index
- 1
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
246 if _variable_index_max
> 0 then
247 visitor
.add_decl
("val_t variable[{_variable_index_max}];")
249 visitor
.add_decl
("val_t *variable = NULL;")
251 if _closurevariable_index
> 0 then
252 visitor
.add_decl
("struct WBT_ *closurevariable[{_closurevariable_index}];")
254 visitor
.add_decl
("struct WBT_ **closurevariable = NULL;")
258 init(v
: CompilerVisitor) do _visitor
= v
261 # A Nit method currenlty compiled
262 class NitMethodContext
263 # Current method compiled
264 readable var _method
: nullable MMMethod
266 # Association between parameters and the corresponding variables
267 readable writable var _method_params
: nullable Array[ParamVariable]
269 # Where a nit return must branch
270 readable writable var _return_label
: nullable String
272 # Where a nit break must branch
273 readable writable var _break_label
: nullable String
275 # Where a nit continue must branch
276 readable writable var _continue_label
: nullable String
278 # Variable where a functionnal nit return must store its value
279 readable writable var _return_value
: nullable String
281 # Variable where a functionnal nit break must store its value
282 readable writable var _break_value
: nullable String
284 # Variable where a functionnal nit continue must store its value
285 readable writable var _continue_value
: nullable String
287 init(method
: nullable MMMethod)
293 ###############################################################################
295 redef class ClosureVariable
296 readable writable var _ctypename
: nullable String
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
303 return "TAG_Bool({global.attr_access}({recv})!=NIT_NULL) /* isset {local_class}::{name}*/"
306 # Compile a read acces on selffor a given reciever.
307 fun compile_read_access
(v
: CompilerVisitor, n
: PNode, recv
: String): String
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 */;")
317 # Compile a write acces on selffor a given reciever.
318 fun compile_write_access(v: CompilerVisitor, n: nullable PNode, recv: String, value: String)
320 v.add_instr("{global.attr_access}({recv}) /*{local_class}::{name}*/ = {value};")
324 redef class MMLocalProperty
325 # Compile the property as a C property
326 fun compile_property_to_c(v: CompilerVisitor) do end
330 # Compile as an expression.
331 # require that signature.return_type != null
332 fun compile_expr_call(v: CompilerVisitor, cargs: Array[String]): String
334 assert signature.return_type != null
335 var s = intern_compile_call(v, cargs)
340 # Compile as a statement.
341 # require that signature.return_type == null
342 fun compile_stmt_call(v: CompilerVisitor, cargs: Array[String])
344 assert signature.return_type == null
345 var s = intern_compile_call(v, cargs)
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
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))
360 var e = i.do_compile_inside(v, cargs)
364 var ee = once "==".to_symbol
365 var ne = once "!=".to_symbol
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}))"
371 if global.is_init then
373 cargs.add("init_table
/*YYY*/")
376 var m = "{global.meth_call}({cargs[0]})"
377 var vcall = "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
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}))"
384 vcall = "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
386 if signature.return_type != null then
389 v.add_instr(vcall + ";")
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
399 if clos_defs != null then arity = clos_defs.length
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
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))
416 for i in [arity..signature.closures.length[ do
417 realcargs.add("NULL")
420 v.nmc.break_value = old_bv
423 var e = intern_compile_call(v, realcargs)
425 v.add_assignment(ve, e)
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) \
{")
434 # A passtrought break or a return is intercepted: go the the next closure
435 v.add_instr("if ({closcns[i]}->has_broke
!= &({ve})) \
{")
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};")
440 # A direct break is interpected
442 # overwrite the returned value in a function
443 v.add_instr("\
} else {ve} = {closcns[i]}->broke_value
;")
445 # Do nothing in a procedure
454 # Compile a call as constructor with given args
455 fun compile_constructor_call(v: CompilerVisitor, recvtype: MMType, cargs: Array[String]): String
457 return "NEW_{recvtype.local_class}_
{global.intro.cname}({cargs.join(", ")}) /*new {recvtype}*/"
460 # Compile a call as call-next-method on self with given args
461 fun compile_super_call(v: CompilerVisitor, cargs: Array[String]): String
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}*/"
469 # Cname of the i-th closure C struct type
470 protected fun closure_cname(i: Int): String
472 return "FWBT_{cname}_
{i}"
475 # Compile and declare the signature to C
476 protected fun decl_csignature(v: CompilerVisitor, args: Array[String]): String
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]}"
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
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(", ")});")
501 if global.is_init then
502 params.add("int
* init_table
")
506 if signature.return_type != null then
512 var p = params.join(", ")
513 var s = "{ret} {cname}({p})"
514 v.add_decl("typedef
{ret} (* {cname}_t
)({p});")
519 redef fun compile_property_to_c(v)
521 v.cfc = new CFunctionContext(v)
523 var args = new Array[String]
525 for i in [0..signature.arity[ do
526 args.add(" param
{i}")
528 for i in [0..signature.closures.length[ do
531 var cs = decl_csignature(v, args)
532 v.add_decl("#define LOCATE_{cname} \"{full_name}\"")
534 v
.add_instr
("{cs} \{")
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;")
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};")
555 var s
= do_compile_inside
(v
, args
)
557 if itpos
!= null then
558 v
.add_instr
("init_table[{itpos}] = 1;")
561 v
.add_instr
("tracehead = trace.prev;")
563 v
.add_instr
("return;")
565 v
.add_instr
("return {s};")
568 v
.cfc
.generate_var_decls
570 ctx_old
.append
(v
.ctx
)
575 for ctx
in v
.out_contexts
do v
.ctx
.merge
(ctx
)
578 # Compile the method body inline
579 fun do_compile_inside
(v
: CompilerVisitor, params
: Array[String]): nullable String is abstract
582 redef class MMReadImplementationMethod
583 redef fun do_compile_inside
(v
, params
)
585 return node
.prop
.compile_read_access
(v
, node
, params
[0])
589 redef class MMWriteImplementationMethod
590 redef fun do_compile_inside
(v
, params
)
592 node
.prop
.compile_write_access
(v
, node
, params
[0], params
[1])
597 redef class MMMethSrcMethod
598 redef fun do_compile_inside
(v
, params
)
600 return node
.do_compile_inside
(v
, self, params
)
604 redef class MMImplicitInit
605 redef fun do_compile_inside
(v
, params
)
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
)
618 sp
.compile_stmt_call
(v
, args
)
620 sp
.compile_stmt_call
(v
, args_recv
)
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
])
632 # Compile a subtype check to self
634 fun compile_cast
(v
: CompilerVisitor, recv
: String, fromtype
: MMType): String
636 # Fixme: handle formaltypes
637 var g
= local_class
.global
639 if fromtype
.is_nullable
then
640 if self.is_nullable
then
641 s
= "({recv}==NIT_NULL) || "
643 s
= "({recv}!=NIT_NULL) && "
646 # FIXME This is used to not break code without the nullable KW
647 s
= "({recv}==NIT_NULL) || "
649 return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
652 # Compile a cast assertion
653 fun compile_type_check
(v
: CompilerVisitor, recv
: String, n
: PNode, fromtype
: MMType)
655 # Fixme: handle formaltypes
656 var g
= local_class
.global
658 if fromtype
.is_nullable
then
659 if self.is_nullable
then
660 s
= "({recv}!=NIT_NULL) && "
662 s
= "({recv}==NIT_NULL) || "
665 # FIXME This is used to not break code without the nullable KW
666 s
= "({recv}!=NIT_NULL) && "
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}*/;")
671 # Compile a notnull cast assertion
672 fun compile_notnull_check
(v
: CompilerVisitor, recv
: String, n
: PNode)
675 v
.add_instr
("if (({recv}==NIT_NULL)) \{ fprintf(stderr, \"Cast failed\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
680 ###############################################################################
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
687 redef class PSignature
688 fun compile_parameters
(v
: CompilerVisitor, orig_sig
: MMSignature, params
: Array[String]) is abstract
691 redef class ASignature
692 redef fun compile_parameters
(v
: CompilerVisitor, orig_sig
: MMSignature, params
: Array[String])
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
)
704 v
.add_assignment
(cname
, params
[ap
.position
])
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]}")
715 redef class AConcreteMethPropdef
716 redef fun do_compile_inside
(v
, method
, params
)
719 v
.nmc
= new NitMethodContext(method
)
721 var selfcname
= v
.cfc
.register_variable
(self_var
)
722 v
.add_assignment
(selfcname
, params
[0])
724 v
.nmc
.method_params
= [self_var
]
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
)
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)
737 v
.compile_stmt
(n_block
)
738 v
.add_instr
("{v.nmc.return_label}: while(false);")
740 var ret
: nullable String = null
741 if method
.signature
.return_type
!= null then
742 ret
= v
.nmc
.return_value
750 redef class ADeferredMethPropdef
751 redef fun do_compile_inside
(v
, method
, params
)
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
764 redef class AExternMethPropdef
765 redef fun do_compile_inside
(v
, method
, params
)
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
)
772 var sig
= method
.signature
773 if params
.length
!= sig
.arity
+ 1 then
774 printl
("par:{params.length} sig:{sig.arity}")
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]))
781 var s
= "{ename}({args.join(", ")})"
782 if sig
.return_type
!= null then
783 return sig
.return_type
.boxtype
(s
)
791 redef class AInternMethPropdef
792 redef fun do_compile_inside
(v
, method
, p
)
794 var c
= method
.local_class
.name
796 var s
: nullable String = null
797 if c
== once
"Int".to_symbol
then
798 if n
== once
"object_id".to_symbol
then
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]}))"
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]}))"
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]}))"
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]}))"
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));")
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]}));")
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
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))))"
955 stderr
.write
("{location}: Fatal error: unknown intern method {method.full_name}.\n")
958 if method
.signature
.return_type
!= null and s
== null then
959 s
= "NIT_NULL /*stub*/"
965 ###############################################################################
968 # Compile the node as an expression
969 # Only the visitor should call it
970 fun compile_expr
(v
: CompilerVisitor): String is abstract
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
977 # Compile the node as a statement
978 # Only the visitor should call it
979 fun compile_stmt
(v
: CompilerVisitor) do printl
("Error!")
982 redef class ABlockExpr
983 redef fun compile_stmt
(v
)
991 redef class AVardeclExpr
992 redef fun prepare_compile_stmt
(v
)
994 v
.cfc
.register_variable
(variable
)
997 redef fun compile_stmt
(v
)
999 var cname
= v
.cfc
.varname
(variable
)
1000 if n_expr
== null then
1001 v
.add_instr
("/*{cname} is variable {variable.name}*/")
1003 var e
= v
.compile_expr
(n_expr
.as(not null))
1004 v
.add_assignment
(cname
, e
)
1009 redef class AReturnExpr
1010 redef fun compile_stmt
(v
)
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
)
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};")
1021 redef class ABreakExpr
1022 redef fun compile_stmt
(v
)
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
)
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};")
1033 redef class AContinueExpr
1034 redef fun compile_stmt
(v
)
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
)
1040 v
.add_instr
("goto {v.nmc.continue_label};")
1044 redef class AAbortExpr
1045 redef fun compile_stmt
(v
)
1047 v
.add_instr
("fprintf(stderr, \"Aborted\
"); {v.printf_locate_error(self)} nit_exit(1);")
1052 redef fun compile_stmt
(v
)
1054 v
.compile_stmt
(n_block
)
1059 redef fun compile_stmt
(v
)
1061 var e
= v
.compile_expr
(n_expr
)
1062 v
.add_instr
("if (UNTAG_Bool({e})) \{ /*if*/")
1064 if n_then
!= null then
1066 v
.compile_stmt
(n_then
)
1069 if n_else
!= null then
1070 v
.add_instr
("} else \{ /*if*/")
1072 v
.compile_stmt
(n_else
)
1079 redef class AIfexprExpr
1080 redef fun compile_expr
(v
)
1082 var e
= v
.compile_expr
(n_expr
)
1083 v
.add_instr
("if (UNTAG_Bool({e})) \{ /*if*/")
1086 var e
= v
.ensure_var
(v
.compile_expr
(n_then
), "Then value")
1088 v
.add_instr
("} else \{ /*if*/")
1091 var e2
= v
.ensure_var
(v
.compile_expr
(n_else
), "Else value")
1092 v
.add_assignment
(e
, e2
)
1099 class AControlableBlock
1101 fun compile_inside_block
(v
: CompilerVisitor) is abstract
1102 redef fun compile_stmt
(v
)
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}"
1110 compile_inside_block
(v
)
1113 v
.nmc
.break_label
= old_break_label
1114 v
.nmc
.continue_label
= old_continue_label
1118 redef class AWhileExpr
1119 special AControlableBlock
1120 redef fun compile_inside_block
(v
)
1122 v
.add_instr
("while (true) \{ /*while*/")
1124 var e
= v
.compile_expr
(n_expr
)
1125 v
.add_instr
("if (!UNTAG_Bool({e})) break; /* while*/")
1127 v
.compile_stmt
(n_block
)
1128 v
.add_instr
("{v.nmc.continue_label}: while(0);")
1131 v
.add_instr
("{v.nmc.break_label}: while(0);")
1135 redef class AForExpr
1136 special AControlableBlock
1137 redef fun compile_inside_block
(v
)
1139 var e
= v
.compile_expr
(n_expr
)
1140 var ittype
= meth_iterator
.signature
.return_type
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*/")
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*/")
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
])
1159 v
.add_instr
("{v.nmc.break_label}: while(0);")
1163 redef class AAssertExpr
1164 redef fun compile_stmt
(v
)
1166 var e
= v
.compile_expr
(n_expr
)
1168 if n_id
!= null then
1169 s
= " '{n_id.text}' "
1171 v
.add_instr
("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit
(1);}")
1175 redef class AVarExpr
1176 redef fun compile_expr(v)
1178 return " {v.cfc.varname(variable)} /*{variable.name}*/"
1182 redef class AVarAssignExpr
1183 redef fun compile_stmt(v)
1185 var e = v.compile_expr(n_value)
1186 v.add_assignment(v.cfc.varname(variable), "{e} /*{variable.name}=*/")
1190 redef class AVarReassignExpr
1191 redef fun compile_stmt(v)
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}*/")
1200 redef class ASelfExpr
1201 redef fun compile_expr(v)
1203 return v.cfc.varname(v.nmc.method_params[0])
1208 redef fun compile_expr(v)
1210 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'or' operand
")
1211 v.add_instr("if (!UNTAG_Bool({e})) \
{ /* or */")
1214 var e2 = v.compile_expr(n_expr2)
1215 v.add_assignment(e, e2)
1222 redef class AAndExpr
1223 redef fun compile_expr(v)
1225 var e = v.ensure_var(v.compile_expr(n_expr), "Left 'and' operand
")
1226 v.add_instr("if (UNTAG_Bool({e})) \
{ /* and */")
1229 var e2 = v.compile_expr(n_expr2)
1230 v.add_assignment(e, e2)
1237 redef class ANotExpr
1238 redef fun compile_expr(v)
1240 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1245 redef fun compile_expr(v)
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}))"
1253 redef class AIsaExpr
1254 redef fun compile_expr(v)
1256 var e = v.compile_expr(n_expr)
1257 return n_type.stype.compile_cast(v, e, n_expr.stype)
1261 redef class AAsCastExpr
1262 redef fun compile_expr(v)
1264 var e = v.compile_expr(n_expr)
1265 n_type.stype.compile_type_check(v, e, self, n_expr.stype)
1270 redef class AAsNotnullExpr
1271 redef fun compile_expr(v)
1273 var e = v.compile_expr(n_expr)
1274 n_expr.stype.compile_notnull_check(v, e, self)
1279 redef class ATrueExpr
1280 redef fun compile_expr(v)
1282 return " TAG_Bool(true)"
1286 redef class AFalseExpr
1287 redef fun compile_expr(v)
1289 return " TAG_Bool(false)"
1293 redef class AIntExpr
1294 redef fun compile_expr(v)
1296 return " TAG_Int({n_number.text})"
1300 redef class AFloatExpr
1301 redef fun compile_expr(v)
1303 return "BOX_Float({n_float.text})"
1307 redef class ACharExpr
1308 redef fun compile_expr(v)
1310 return " TAG_Char({n_char.text})"
1314 redef class AStringFormExpr
1315 redef fun compile_expr(v)
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 \
{")
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};")
1333 # The raw string value
1334 protected fun string_text: String is abstract
1336 # The string in a C native format
1337 protected var _cstring: nullable String
1339 # The string length in bytes
1340 protected var _cstring_length: nullable Int
1342 # Compute _cstring and _cstring_length using string_text
1343 protected fun compute_string_info
1346 var str = string_text
1347 var res = new Buffer
1349 while i < str.length do
1354 if c2 != '{' and c2 != '}' then
1364 _cstring_length = len
1368 redef class AStringExpr
1369 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1371 redef class AStartStringExpr
1372 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1374 redef class AMidStringExpr
1375 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1377 redef class AEndStringExpr
1378 redef fun string_text do return n_string.text.substring(1, n_string.text.length - 2)
1381 redef class ASuperstringExpr
1382 redef fun compile_expr(v)
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
)")
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
1391 e = meth_to_s.compile_expr_call(v, [e])
1394 meth_add.compile_stmt_call(v, [array, e])
1397 return meth_to_s.compile_expr_call(v, [array])
1401 redef class ANullExpr
1402 redef fun compile_expr(v)
1404 return " NIT_NULL /*null*/"
1408 redef class AArrayExpr
1409 redef fun compile_expr(v)
1411 var recv = meth_with_capacity.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1412 recv = v.ensure_var(recv, "Literal array
")
1414 for ne in n_exprs do
1415 var e = v.compile_expr(ne)
1416 meth_add.compile_stmt_call(v, [recv, e])
1422 redef class ARangeExpr
1423 redef fun compile_expr(v)
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])
1431 redef class ASuperExpr
1432 redef fun compile_stmt(v)
1434 var e = intern_compile_call(v)
1436 v.add_instr(e + ";")
1440 redef fun compile_expr(v)
1442 var e = intern_compile_call(v)
1447 private fun intern_compile_call(v: CompilerVisitor): nullable String
1449 var arity = v.nmc.method_params.length - 1
1450 if init_in_superclass != null then
1451 arity = init_in_superclass.signature.arity
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]))
1461 args.add(v.compile_expr(na))
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)
1468 return prop.compile_super_call(v, args)
1473 redef class AAttrExpr
1474 redef fun compile_expr(v)
1476 var e = v.compile_expr(n_expr)
1477 return prop.compile_read_access(v, n_id, e)
1481 redef class AAttrAssignExpr
1482 redef fun compile_stmt(v)
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)
1489 redef class AAttrReassignExpr
1490 redef fun compile_stmt(v)
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)
1500 redef class AIssetAttrExpr
1501 redef fun compile_expr(v)
1503 var e = v.compile_expr(n_expr)
1504 return prop.compile_isset(v, n_id, e)
1508 redef class AAbsAbsSendExpr
1509 # Compile each argument and add them to the array
1510 fun compile_arguments_in(v: CompilerVisitor, cargs: Array[String])
1512 for a in arguments do
1513 cargs.add(v.compile_expr(a))
1519 redef class ASendExpr
1520 private fun intern_compile_call(v: CompilerVisitor): nullable String
1522 var recv = v.compile_expr(n_expr)
1523 var cargs = new Array[String]
1525 compile_arguments_in(v, cargs)
1527 var e: nullable String
1528 if prop_signature.closures.is_empty then
1529 e = prop.intern_compile_call(v, cargs)
1531 e = prop.compile_call_and_closures(v, cargs, closure_defs)
1534 if prop.global.is_init then
1535 v.invoke_super_init_calls_after(prop)
1540 redef fun compile_expr(v)
1542 var e = intern_compile_call(v)
1547 redef fun compile_stmt(v)
1549 var e = intern_compile_call(v)
1551 v.add_instr(e + ";")
1556 redef class ASendReassignExpr
1557 redef fun compile_expr(v) do abort
1559 redef fun compile_stmt(v)
1561 var recv = v.compile_expr(n_expr)
1562 var cargs = new Array[String]
1564 compile_arguments_in(v, cargs)
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])
1570 prop.compile_stmt_call(v, cargs)
1574 redef class ANewExpr
1575 redef fun compile_expr(v)
1577 var cargs = new Array[String]
1578 compile_arguments_in(v, cargs)
1579 return prop.compile_constructor_call(v, stype, cargs)
1582 redef fun compile_stmt(v) do abort
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
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
1594 redef class AClosureDef
1595 # The cname of the function
1596 readable var _cname: nullable String
1598 redef fun compile_closure(v, closcn)
1601 v.ctx = new CContext
1602 v.out_contexts.add(v.ctx)
1604 var cfc_old = v.cfc.closure
1605 v.cfc.closure = v.nmc
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}"
1614 var cname = "OC_{v.nmc.method.cname}_
{v.out_contexts.length}"
1616 var args = new Array[String]
1617 for i in [0..closure.signature.arity[ do
1618 args.add(" param
{i}")
1621 var cs = decl_csignature(v, args, closcn)
1623 v.add_instr("{cs} \
{")
1625 var ctx_old2 = v.ctx
1626 v.ctx = new CContext
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
;")
1631 v.add_instr("trace
.file
= LOCATE_{v.module.name};")
1632 var s = do_compile_inside(v, args)
1634 v.add_instr("{v.nmc.return_label}:")
1635 v.add_instr("tracehead
= trace
.prev
;")
1637 v.add_instr("return;")
1639 v.add_instr("return {s};")
1642 ctx_old2.append(v.ctx)
1648 v.cfc.closure = cfc_old
1649 v.nmc.return_value = old_rv
1650 v.nmc.break_value = old_bv
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
;")
1661 v.add_instr("{closcnv}.variable
= variable
;")
1662 v.add_instr("{closcnv}.closurevariable
= closurevariable
;")
1665 return "(&{closcnv})"
1668 protected fun decl_csignature(v: CompilerVisitor, args: Array[String], closcn: String): String
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]}"
1677 if closure.signature.return_type != null then
1682 var p = params.join(", ")
1683 var s = "{ret} {cname}({p})"
1684 v.add_decl("typedef
{ret} (* {cname}_t
)({p});")
1689 redef fun do_compile_inside(v, params)
1691 for i in [0..variables.length[ do
1692 var vacname = v.cfc.register_variable(variables[i])
1693 v.add_assignment(vacname, params[i])
1696 var old_cv = v.nmc.continue_value
1697 var old_cl = v.nmc.continue_label
1698 var old_bl = v.nmc.break_label
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
1704 v.compile_stmt(n_expr)
1706 v.add_instr("{v.nmc.continue_label}: while(false);")
1708 var ret: nullable String = null
1709 if closure.signature.return_type != null then ret = v.nmc.continue_value
1711 v.nmc.continue_value = old_cv
1712 v.nmc.continue_label = old_cl
1713 v.nmc.break_label = old_bl
1719 redef class PClosureDecl
1720 fun do_compile_inside(v: CompilerVisitor, params: Array[String]): nullable String is abstract
1722 redef class AClosureDecl
1723 redef fun do_compile_inside(v, params)
1725 n_signature.compile_parameters(v, variable.closure.signature, params)
1727 var old_cv = v.nmc.continue_value
1728 var old_cl = v.nmc.continue_label
1729 var old_bl = v.nmc.break_label
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
1735 v.compile_stmt(n_expr)
1737 v.add_instr("{v.nmc.continue_label}: while(false);")
1739 var ret: nullable String = null
1740 if variable.closure.signature.return_type != null then ret = v.nmc.continue_value
1742 v.nmc.continue_value = old_cv
1743 v.nmc.continue_label = old_cl
1744 v.nmc.break_label = old_bl
1750 redef class AClosureCallExpr
1751 fun intern_compile_call(v: CompilerVisitor): nullable String
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
")
1758 if variable.closure.is_optional then
1759 v.add_instr("if({v.cfc.varname(variable)}==NULL) \
{")
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)
1766 v.add_instr("} else \
{")
1770 var ivar = v.cfc.varname(variable)
1772 cargs2.append(cargs)
1773 var s = "(({variable.ctypename})({ivar}->fun))({cargs2.join(", ")}) /* Invoke closure
{variable} */"
1775 v.add_assignment(va, s)
1779 v.add_instr("if ({ivar}->has_broke
) \
{")
1781 if n_closure_defs.length == 1 then do
1782 n_closure_defs.first.do_compile_inside(v, null)
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};")
1789 if variable.closure.is_optional then
1796 redef fun compile_expr(v)
1798 var e = intern_compile_call(v)
1803 redef fun compile_stmt(v)
1805 var e = intern_compile_call(v)
1807 v.add_instr(e + ";")
1812 redef class AProxyExpr
1813 redef fun compile_expr(v)
1815 return v.compile_expr(n_expr)
1819 redef class AOnceExpr
1820 redef fun compile_expr(v)
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 \
{")
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;")