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 meth compile_stmt
(n
: PExpr)
27 n
.prepare_compile_stmt
(self)
28 var i
= cfc
._variable_index
30 cfc
._variable_index
= i
33 # Compile is expression node
34 meth compile_expr
(n
: PExpr): String
36 var i
= cfc
._variable_index
37 var s
= n
.compile_expr
(self)
38 cfc
._variable_index
= i
47 # Ensure that a c expression is a var
48 meth ensure_var
(s
: String): String
50 if s
.substring
(0,3) == "variable" then
58 # Add a assignment between a variable and an expression
59 meth add_assignment
(v
: String, s
: String)
62 add_instr
("{v} = {s};")
66 readable writable attr _cfc
: CFunctionContext
68 readable writable attr _nmc
: NitMethodContext
70 # Generate an fprintf to display an error location
71 meth printf_locate_error
(node
: PNode): String
73 var s
= "fprintf(stderr, \""
74 if nmc != null then s.append(" in %s
")
75 s.append(" (%s
:%d
)\\n\
", ")
76 if nmc
!= null then s
.append
("LOCATE_{nmc.method.cname}, ")
77 s
.append
("LOCATE_{module.name}, {node.line_number});")
81 redef init(module: MMSrcModule)
86 meth invoke_super_init_calls_after
(start_prop
: MMMethod)
88 var n
= nmc
.method
.node
89 assert n
isa AConcreteInitPropdef
91 if n
.super_init_calls
.is_empty
then return
95 if start_prop
!= null then
96 while n
.super_init_calls
[i
] != start_prop
do
97 #s.append(" {n.super_init_calls[i]}")
101 #s.append(" {start_prop}")
103 while n
.explicit_super_init_calls
[j
] != start_prop
do
108 var stop_prop
: MMMethod = null
109 if j
< n
.explicit_super_init_calls
.length
then
110 stop_prop
= n
.explicit_super_init_calls
[j
]
112 var l
= n
.super_init_calls
.length
115 var p
= n
.super_init_calls
[i
]
116 if p
== stop_prop
then break
117 var cargs
= nmc
.method_params
118 if p
.signature
.arity
== 0 then
119 cargs
= [nmc
.method_params
[0]]
122 p
.compile_call
(self, cargs
)
127 # s.append(" {n.super_init_calls[i]}")
130 #if stop_prop != null then s.append(" (stop at {stop_prop})")
131 #n.printl("implicit calls in {n.method}: {s}")
135 # A C function currently written
136 class CFunctionContext
137 readable attr _visitor
: CompilerVisitor
139 # Next available variable number
140 attr _variable_index
: Int = 0
142 # Total number of variable
143 attr _variable_index_max
: Int = 0
145 # Association between nit variable and the corrsponding c variable
146 attr _varnames
: Map[Variable, String] = new HashMap[Variable, String]
148 meth varname
(v
: Variable): String
153 # Return the next available variable
156 var v
= variable
(_variable_index
)
157 _variable_index
= _variable_index
+ 1
158 if _variable_index
> _variable_index_max
then
159 _variable_index_max
= _variable_index
164 meth register_variable
(v
: Variable): String
167 _varnames
[v
] = "variable[{_variable_index-1}]"
171 # Return the ith variable
172 protected meth variable
(i
: Int): String
174 return "variable[{i}]"
177 # Mark the variable available
178 meth free_var
(v
: String)
181 if v
== variable
(_variable_index-1
) then
182 _variable_index
= _variable_index
- 1
186 # Generate the local variable declarations
187 # To use at the end of the C function once all variables are known
188 meth generate_var_decls
190 if _variable_index_max
> 0 then
191 visitor
.add_decl
("val_t variable[{_variable_index_max}];")
193 visitor
.add_decl
("val_t *variable = NULL;")
197 init(v
: CompilerVisitor) do _visitor
= v
200 # A Nit method currenlty compiled
201 class NitMethodContext
202 # Current method compiled
203 readable attr _method
: MMSrcMethod
205 # Is a "return" found in the method body
206 readable writable attr _has_return
: Bool = false
208 # Association between parameters and the corresponding c variables
209 readable writable attr _method_params
: Array[String]
211 # Where a nit return must branch
212 readable writable attr _return_label
: String
214 # Where a nit break must branch
215 readable writable attr _break_label
: String
217 # Where a nit continue must branch
218 readable writable attr _continue_label
: String
220 # Variable where a functionnal nit return must store its value
221 readable writable attr _return_value
: String
223 init(method
: MMSrcMethod)
229 ###############################################################################
232 # Compile a call on self for given arguments
233 # Most calls are compiled with a table access,
234 # primitive calles are inlined
235 # == and != are guarded and possibly inlined
236 meth compile_call
(v
: CompilerVisitor, cargs
: Array[String]): String
239 if i
isa MMSrcMethod then
240 if i
isa MMMethSrcMethod and i
.node
isa AInternMethPropdef or
241 (i
.local_class
.name
== (once
"Array".to_symbol
) and name
== (once
"[]".to_symbol
))
243 var e
= i
.do_compile_inside
(v
, cargs
)
247 var ee
= once
"==".to_symbol
248 var ne
= once
"!=".to_symbol
250 var eqp
= signature
.recv
.local_class
.select_method
(ee
)
251 var eqcall
= eqp
.compile_call
(v
, cargs
)
252 return "TAG_Bool(!UNTAG_Bool({eqcall}))"
254 if global
.is_init
then
256 cargs
.add
("init_table /*YYY*/")
259 var m
= "(({cname}_t)CALL({cargs[0]},{global.color_id}))"
260 var vcall
= "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
262 vcall
= "UNTAG_Bool({vcall})"
263 var obj
= once
"Object".to_symbol
264 if i
.local_class
.name
== obj
then
265 vcall
= "(({m}=={i.cname})?(IS_EQUAL_NN({cargs[0]},{cargs[1]})):({vcall}))"
267 vcall
= "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
269 if signature
.return_type
!= null then
272 v
.add_instr
(vcall
+ ";")
277 # Compile a call as constructor with given args
278 meth compile_constructor_call
(v
: CompilerVisitor, recvtype
: MMType, cargs
: Array[String]): String
280 var recv
= v
.cfc
.get_var
281 v
.add_instr
("{recv} = NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}); /*new {recvtype}*/")
285 # Compile a call as call-next-method on self with given args
286 meth compile_super_call
(v
: CompilerVisitor, cargs
: Array[String]): String
288 var m
= "(({cname}_t)CALL({cargs[0]},{color_id_for_super}))"
289 var vcall
= "{m}({cargs.join(", ")}) /*super {local_class}::{name}*/"
294 redef class MMAttribute
295 # Compile an acces on selffor a given reciever.
296 # Result is a valid C left-value for assigment
297 meth compile_access
(v
: CompilerVisitor, recv
: String): String
299 return "{global.attr_access}({recv}) /*{local_class}::{name}*/"
303 redef class MMLocalProperty
304 # Compile the property as a C property
305 meth compile_property_to_c
(v
: CompilerVisitor) do end
308 redef class MMSrcMethod
309 # Compile and declare the signature to C
310 protected meth decl_csignature
(v
: CompilerVisitor, args
: Array[String]): String
312 var params
= new Array[String]
313 var params_new
: Array[String] = null
314 if global
.is_init
then
315 params_new
= new Array[String]
317 params
.add
("val_t {args[0]}")
318 for i
in [0..signature
.arity
[ do
319 var p
= "val_t {args[i+1]}"
321 if params_new
!= null then params_new
.add
(p
)
323 if global
.is_init
then
324 params
.add
("int* init_table")
327 if signature
.return_type
!= null then
332 var p
= params
.join
(", ")
333 var s
= "{ret} {cname}({p})"
334 v
.add_decl
("typedef {ret} (* {cname}_t)({p});")
336 if params_new
!= null then
337 v
.add_decl
("val_t NEW_{cname}({params_new.join(", ")});")
342 redef meth compile_property_to_c
(v
)
344 v
.cfc
= new CFunctionContext(v
)
346 var args
= new Array[String]
348 for i
in [0..signature
.arity
[ do
349 args
.add
(" param{i}")
351 var cs
= decl_csignature
(v
, args
)
352 v
.add_decl
("#define LOCATE_{cname} \"{full_name}\
"")
354 v
.add_instr
("{cs} \{")
361 if s
.node
!= null then ln
= s
.node
.line_number
362 v
.add_decl
("struct trace_t trace = \{NULL, NULL, {ln}, LOCATE_{cname}};")
363 v
.add_instr
("trace.prev = tracehead; tracehead = &trace;")
364 v
.add_instr
("trace.file = LOCATE_{module.name};")
365 var s
= do_compile_inside
(v
, args
)
366 v
.add_instr
("tracehead = trace.prev;")
368 v
.add_instr
("return;")
370 v
.add_instr
("return {s};")
373 v
.cfc
.generate_var_decls
375 ctx_old
.append
(v
.ctx
)
381 # Compile the method body inline
382 meth do_compile_inside
(v
: CompilerVisitor, params
: Array[String]): String is abstract
385 redef class MMReadImplementationMethod
386 redef meth do_compile_inside
(v
, params
)
388 return node
.prop
.compile_access
(v
, params
[0])
392 redef class MMWriteImplementationMethod
393 redef meth do_compile_inside
(v
, params
)
395 v
.add_assignment
(node
.prop
.compile_access
(v
, params
[0]), params
[1])
400 redef class MMMethSrcMethod
401 redef meth do_compile_inside
(v
, params
)
403 return node
.do_compile_inside
(v
, self, params
)
407 redef class MMImplicitInit
408 redef meth do_compile_inside
(v
, params
)
410 var f
= params
.length
- unassigned_attributes
.length
411 var recv
= params
.first
412 for sp
in super_inits
do
413 assert sp
isa MMMethod
414 var args_recv
= [recv
]
415 if sp
== super_init
then
416 var args
= new Array[String].with_capacity
(f
)
421 sp
.compile_call
(v
, args
)
423 sp
.compile_call
(v
, args_recv
)
426 for i
in [f
..params
.length
[ do
427 var attribute
= unassigned_attributes
[i-f
]
428 v
.add_assignment
(attribute
.compile_access
(v
, recv
), params
[i
])
435 # Compile a subtype check to self
437 meth compile_cast
(v
: CompilerVisitor, recv
: String): String
439 # Fixme: handle formaltypes
440 var g
= local_class
.global
441 return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
444 # Compile a cast assertion
445 meth compile_type_check
(v
: CompilerVisitor, recv
: String, n
: PNode)
447 # Fixme: handle formaltypes
448 var g
= local_class
.global
449 v
.add_instr
("if (({recv}!=NIT_NULL) && !VAL_ISA({recv}, {g.color_id}, {g.id_id})) \{ fprintf(stderr, \"Cast failled\"); {v.printf_locate_error(n)} nit_exit(1); } /*cast {self}*/;")
453 ###############################################################################
455 redef class AMethPropdef
456 # Compile the method body
457 meth do_compile_inside
(v
: CompilerVisitor, method
: MMSrcMethod, params
: Array[String]): String is abstract
460 redef class AConcreteMethPropdef
461 redef meth do_compile_inside
(v
, method
, params
)
464 v
.nmc
= new NitMethodContext(method
)
466 var orig_meth
: MMLocalProperty = method
.global
.intro
467 var orig_sig
= orig_meth
.signature_for
(method
.signature
.recv
)
468 if n_signature
!= null then
469 var sig
= n_signature
470 assert sig
isa ASignature
471 for ap
in sig
.n_params
do
472 var cname
= v
.cfc
.register_variable
(ap
.variable
)
473 var orig_type
= orig_sig
[ap
.position
]
474 if not orig_type
< ap
.variable
.stype
then
475 # FIXME: do not test always
476 # FIXME: handle formal types
477 v
.add_instr
("/* check if p<{ap.variable.stype} with p:{orig_type} */")
478 ap
.variable
.stype
.compile_type_check
(v
, params
[ap
.position
+ 1], ap
)
480 v
.add_assignment
(cname
, params
[ap
.position
+ 1])
484 var itpos
: String = null
485 if self isa AConcreteInitPropdef then
486 itpos
= "VAL2OBJ({params[0]})->vft[{method.local_class.global.init_table_pos_id}].i"
487 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
488 v
.add_instr
("if (init_table[{itpos}]) return;")
491 v
.nmc
.method_params
= params
492 v
.nmc
.return_label
= "return_label{v.new_number}"
493 if method
.signature
.return_type
!= null then
494 v
.nmc
.return_value
= v
.cfc
.get_var
495 v
.cfc
.free_var
(v
.nmc
.return_value
)
497 v
.nmc
.return_value
= null
499 if self isa AConcreteInitPropdef then
500 v
.invoke_super_init_calls_after
(null)
502 if n_block
!= null then
503 v
.compile_stmt
(n_block
)
505 if v
.nmc
.has_return
then
506 v
.add_instr
("{v.nmc.return_label}: while(false);")
508 if self isa AConcreteInitPropdef then
509 v
.add_instr
("init_table[{itpos}] = 1;")
511 var ret
= v
.nmc
.return_value
518 redef class ADeferredMethPropdef
519 redef meth do_compile_inside
(v
, method
, params
)
521 v
.add_instr
("fprintf(stderr, \"Deferred method
%s called\
");")
522 v
.add_instr
(v
.printf_locate_error
(self))
523 v
.add_instr
("nit_exit(1);")
524 if method
.signature
.return_type
!= null then
532 redef class AExternMethPropdef
533 redef meth do_compile_inside
(v
, method
, params
)
535 var ename
= "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
536 if n_extern
!= null then
537 ename
= n_extern
.text
538 ename
= ename
.substring
(1, ename
.length-2
)
540 var sig
= method
.signature
541 if params
.length
!= sig
.arity
+ 1 then
542 printl
("par:{params.length} sig:{sig.arity}")
544 var args
= new Array[String]
545 args
.add
(sig
.recv
.unboxtype
(params
[0]))
546 for i
in [0..sig
.arity
[ do
547 args
.add
(sig
[i
].unboxtype
(params
[i
+1]))
549 var s
= "{ename}({args.join(", ")})"
550 if sig
.return_type
!= null then
551 return sig
.return_type
.boxtype
(s
)
559 redef class AInternMethPropdef
560 redef meth do_compile_inside
(v
, method
, p
)
562 var c
= method
.local_class
.name
565 if c
== once
"Int".to_symbol
then
566 if n
== once
"object_id".to_symbol
then
568 else if n
== once
"unary -".to_symbol
then
569 s
= "TAG_Int(-UNTAG_Int({p[0]}))"
570 else if n
== once
"output".to_symbol
then
571 v
.add_instr
("printf(\"%d\\n\
", UNTAG_Int({p[0]}));")
572 else if n
== once
"ascii".to_symbol
then
573 s
= "TAG_Char(UNTAG_Int({p[0]}))"
574 else if n
== once
"succ".to_symbol
then
575 s
= "TAG_Int(UNTAG_Int({p[0]})+1)"
576 else if n
== once
"prec".to_symbol
then
577 s
= "TAG_Int(UNTAG_Int({p[0]})-1)"
578 else if n
== once
"to_f".to_symbol
then
579 s
= "BOX_Float((float)UNTAG_Int({p[0]}))"
580 else if n
== once
"+".to_symbol
then
581 s
= "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
582 else if n
== once
"-".to_symbol
then
583 s
= "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
584 else if n
== once
"*".to_symbol
then
585 s
= "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
586 else if n
== once
"/".to_symbol
then
587 s
= "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
588 else if n
== once
"%".to_symbol
then
589 s
= "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
590 else if n
== once
"<".to_symbol
then
591 s
= "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
592 else if n
== once
">".to_symbol
then
593 s
= "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
594 else if n
== once
"<=".to_symbol
then
595 s
= "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
596 else if n
== once
">=".to_symbol
then
597 s
= "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
598 else if n
== once
"lshift".to_symbol
then
599 s
= "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
600 else if n
== once
"rshift".to_symbol
then
601 s
= "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
602 else if n
== once
"==".to_symbol
then
603 s
= "TAG_Bool(({p[0]})==({p[1]}))"
604 else if n
== once
"!=".to_symbol
then
605 s
= "TAG_Bool(({p[0]})!=({p[1]}))"
607 else if c
== once
"Float".to_symbol
then
608 if n
== once
"object_id".to_symbol
then
609 s
= "TAG_Int((bigint)UNBOX_Float({p[0]}))"
610 else if n
== once
"unary -".to_symbol
then
611 s
= "BOX_Float(-UNBOX_Float({p[0]}))"
612 else if n
== once
"output".to_symbol
then
613 v
.add_instr
("printf(\"%f\\n\
", UNBOX_Float({p[0]}));")
614 else if n
== once
"to_i".to_symbol
then
615 s
= "TAG_Int((bigint)UNBOX_Float({p[0]}))"
616 else if n
== once
"+".to_symbol
then
617 s
= "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
618 else if n
== once
"-".to_symbol
then
619 s
= "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
620 else if n
== once
"*".to_symbol
then
621 s
= "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
622 else if n
== once
"/".to_symbol
then
623 s
= "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
624 else if n
== once
"<".to_symbol
then
625 s
= "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
626 else if n
== once
">".to_symbol
then
627 s
= "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
628 else if n
== once
"<=".to_symbol
then
629 s
= "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
630 else if n
== once
">=".to_symbol
then
631 s
= "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
633 else if c
== once
"Char".to_symbol
then
634 if n
== once
"object_id".to_symbol
then
635 s
= "TAG_Int(UNTAG_Char({p[0]}))"
636 else if n
== once
"unary -".to_symbol
then
637 s
= "TAG_Char(-UNTAG_Char({p[0]}))"
638 else if n
== once
"output".to_symbol
then
639 v
.add_instr
("printf(\"%c\
", (unsigned char)UNTAG_Char({p[0]}));")
640 else if n
== once
"ascii".to_symbol
then
641 s
= "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
642 else if n
== once
"succ".to_symbol
then
643 s
= "TAG_Char(UNTAG_Char({p[0]})+1)"
644 else if n
== once
"prec".to_symbol
then
645 s
= "TAG_Char(UNTAG_Char({p[0]})-1)"
646 else if n
== once
"to_i".to_symbol
then
647 s
= "TAG_Int(UNTAG_Char({p[0]})-'0')"
648 else if n
== once
"+".to_symbol
then
649 s
= "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
650 else if n
== once
"-".to_symbol
then
651 s
= "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
652 else if n
== once
"*".to_symbol
then
653 s
= "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
654 else if n
== once
"/".to_symbol
then
655 s
= "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
656 else if n
== once
"%".to_symbol
then
657 s
= "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
658 else if n
== once
"<".to_symbol
then
659 s
= "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
660 else if n
== once
">".to_symbol
then
661 s
= "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
662 else if n
== once
"<=".to_symbol
then
663 s
= "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
664 else if n
== once
">=".to_symbol
then
665 s
= "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
666 else if n
== once
"==".to_symbol
then
667 s
= "TAG_Bool(({p[0]})==({p[1]}))"
668 else if n
== once
"!=".to_symbol
then
669 s
= "TAG_Bool(({p[0]})!=({p[1]}))"
671 else if c
== once
"Bool".to_symbol
then
672 if n
== once
"object_id".to_symbol
then
673 s
= "TAG_Int(UNTAG_Bool({p[0]}))"
674 else if n
== once
"unary -".to_symbol
then
675 s
= "TAG_Bool(-UNTAG_Bool({p[0]}))"
676 else if n
== once
"output".to_symbol
then
677 v
.add_instr
("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\
":\"false\\n\
");")
678 else if n
== once
"ascii".to_symbol
then
679 s
= "TAG_Bool(UNTAG_Bool({p[0]}))"
680 else if n
== once
"to_i".to_symbol
then
681 s
= "TAG_Int(UNTAG_Bool({p[0]}))"
682 else if n
== once
"==".to_symbol
then
683 s
= "TAG_Bool(({p[0]})==({p[1]}))"
684 else if n
== once
"!=".to_symbol
then
685 s
= "TAG_Bool(({p[0]})!=({p[1]}))"
687 else if c
== once
"NativeArray".to_symbol
then
688 if n
== once
"object_id".to_symbol
then
689 s
= "TAG_Int(UNBOX_NativeArray({p[0]}))"
690 else if n
== once
"[]".to_symbol
then
691 s
= "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
692 else if n
== once
"[]=".to_symbol
then
693 v
.add_instr
("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
694 else if n
== once
"copy_to".to_symbol
then
695 v
.add_instr
("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
697 else if c
== once
"NativeString".to_symbol
then
698 if n
== once
"object_id".to_symbol
then
699 s
= "TAG_Int(UNBOX_NativeString({p[0]}))"
700 else if n
== once
"atoi".to_symbol
then
701 s
= "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
702 else if n
== once
"[]".to_symbol
then
703 s
= "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
704 else if n
== once
"[]=".to_symbol
then
705 v
.add_instr
("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
706 else if n
== once
"copy_to".to_symbol
then
707 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]}));")
709 else if n
== once
"object_id".to_symbol
then
710 s
= "TAG_Int((bigint){p[0]})"
711 else if n
== once
"sys".to_symbol
then
713 else if n
== once
"is_same_type".to_symbol
then
714 s
= "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
715 else if n
== once
"exit".to_symbol
then
716 v
.add_instr
("exit(UNTAG_Int({p[1]}));")
717 else if n
== once
"calloc_array".to_symbol
then
718 s
= "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
719 else if n
== once
"calloc_string".to_symbol
then
720 s
= "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
723 v
.add_instr
("fprintf(stderr, \"Intern {n}\\n\
"); nit_exit(1);")
725 if method
.signature
.return_type
!= null and s
== null then
726 s
= "NIT_NULL /*stub*/"
732 ###############################################################################
735 # Compile the node as an expression
736 # Only the visitor should call it
737 meth compile_expr
(v
: CompilerVisitor): String is abstract
739 # Prepare a call of node as a statement
740 # Only the visitor should call it
741 # It's used for local variable managment
742 meth prepare_compile_stmt
(v
: CompilerVisitor) do end
744 # Compile the node as a statement
745 # Only the visitor should call it
746 meth compile_stmt
(v
: CompilerVisitor) do printl
("Error!")
749 redef class ABlockExpr
750 redef meth compile_stmt
(v
)
758 redef class AVardeclExpr
759 redef meth prepare_compile_stmt
(v
)
761 v
.cfc
.register_variable
(variable
)
764 redef meth compile_stmt
(v
)
766 var cname
= v
.cfc
.varname
(variable
)
767 if n_expr
== null then
768 var t
= variable
.stype
769 v
.add_assignment
(cname
, "{t.default_cvalue} /*decl variable {variable.name}*/")
771 var e
= v
.compile_expr
(n_expr
)
772 v
.add_assignment
(cname
, e
)
777 redef class AReturnExpr
778 redef meth compile_stmt
(v
)
780 v
.nmc
.has_return
= true
781 if n_expr
!= null then
782 var e
= v
.compile_expr
(n_expr
)
783 v
.add_assignment
(v
.nmc
.return_value
, e
)
785 v
.add_instr
("goto {v.nmc.return_label};")
789 redef class ABreakExpr
790 redef meth compile_stmt
(v
)
792 v
.add_instr
("goto {v.nmc.break_label};")
796 redef class AContinueExpr
797 redef meth compile_stmt
(v
)
799 v
.add_instr
("goto {v.nmc.continue_label};")
803 redef class AAbortExpr
804 redef meth compile_stmt
(v
)
806 v
.add_instr
("fprintf(stderr, \"Aborted\
"); {v.printf_locate_error(self)} nit_exit(1);")
811 redef meth compile_stmt
(v
)
813 if n_block
!= null then
814 v
.compile_stmt
(n_block
)
820 redef meth compile_stmt
(v
)
822 var e
= v
.compile_expr
(n_expr
)
823 v
.add_instr
("if (UNTAG_Bool({e})) \{ /*if*/")
825 if n_then
!= null then
827 v
.compile_stmt
(n_then
)
830 if n_else
!= null then
831 v
.add_instr
("} else \{ /*if*/")
833 v
.compile_stmt
(n_else
)
840 redef class AIfexprExpr
841 redef meth compile_expr
(v
)
843 var e
= v
.compile_expr
(n_expr
)
844 v
.add_instr
("if (UNTAG_Bool({e})) \{ /*if*/")
847 var e
= v
.ensure_var
(v
.compile_expr
(n_then
))
849 v
.add_instr
("} else \{ /*if*/")
852 var e2
= v
.ensure_var
(v
.compile_expr
(n_else
))
853 v
.add_assignment
(e
, e2
)
860 redef class AControlableBlock
861 meth compile_inside_block
(v
: CompilerVisitor) is abstract
862 redef meth compile_stmt
(v
)
864 var old_break_label
= v
.nmc
.break_label
865 var old_continue_label
= v
.nmc
.continue_label
866 var id
= v
.new_number
867 v
.nmc
.break_label
= "break_{id}"
868 v
.nmc
.continue_label
= "continue_{id}"
870 compile_inside_block
(v
)
873 v
.nmc
.break_label
= old_break_label
874 v
.nmc
.continue_label
= old_continue_label
878 redef class AWhileExpr
879 redef meth compile_inside_block
(v
)
881 v
.add_instr
("while (true) \{ /*while*/")
883 var e
= v
.compile_expr
(n_expr
)
884 v
.add_instr
("if (!UNTAG_Bool({e})) break; /* while*/")
886 if n_block
!= null then
887 v
.compile_stmt
(n_block
)
889 v
.add_instr
("{v.nmc.continue_label}: while(0);")
892 v
.add_instr
("{v.nmc.break_label}: while(0);")
897 redef meth compile_inside_block
(v
)
899 v
.compile_stmt
(n_vardecl
)
903 redef class AForVardeclExpr
904 redef meth compile_stmt
(v
)
906 var e
= v
.compile_expr
(n_expr
)
907 var prop
= n_expr
.stype
.local_class
.select_method
(once
"iterator".to_symbol
)
909 printl
("No iterator")
912 var ittype
= prop
.signature
.return_type
914 var iter
= v
.cfc
.get_var
915 v
.add_assignment
(iter
, prop
.compile_call
(v
, [e
]))
916 var prop2
= ittype
.local_class
.select_method
(once
"is_ok".to_symbol
)
917 if prop2
== null then
921 var prop3
= ittype
.local_class
.select_method
(once
"item".to_symbol
)
922 if prop3
== null then
926 var prop4
= ittype
.local_class
.select_method
(once
"next".to_symbol
)
927 if prop4
== null then
931 v
.add_instr
("while (true) \{ /*for*/")
933 var ok
= v
.cfc
.get_var
934 v
.add_assignment
(ok
, prop2
.compile_call
(v
, [iter
]))
935 v
.add_instr
("if (!UNTAG_Bool({ok})) break; /*for*/")
937 var e
= prop3
.compile_call
(v
, [iter
])
939 var cname
= v
.cfc
.register_variable
(variable
)
940 v
.add_assignment
(cname
, e
)
942 assert par
isa AForExpr
943 var n_block
= par
.n_block
944 if n_block
!= null then
945 v
.compile_stmt
(n_block
)
947 v
.add_instr
("{v.nmc.continue_label}: while(0);")
948 e
= prop4
.compile_call
(v
, [iter
])
952 v
.add_instr
("{v.nmc.break_label}: while(0);")
956 redef class AAssertExpr
957 redef meth compile_stmt
(v
)
959 var e
= v
.compile_expr
(n_expr
)
962 s
= " '{n_id.text}' "
964 v
.add_instr
("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit
(1);}")
969 redef meth compile_expr(v)
971 return " {v.cfc.varname(variable)} /*{variable.name}*/"
975 redef class AVarAssignExpr
976 redef meth compile_stmt(v)
978 var e = v.compile_expr(n_value)
979 v.add_assignment(v.cfc.varname(variable), "{e} /*{variable.name}=*/")
983 redef class AVarReassignExpr
984 redef meth compile_stmt(v)
986 var e1 = v.cfc.varname(variable)
987 var e2 = v.compile_expr(n_value)
988 var e3 = assign_method.compile_call(v, [e1, e2])
989 v.add_assignment(v.cfc.varname(variable), "{e3} /*{variable.name}*/")
993 redef class ASelfExpr
994 redef meth compile_expr(v)
996 return v.nmc.method_params[0]
1001 redef meth compile_expr(v)
1003 var e = v.ensure_var(v.compile_expr(n_expr))
1004 v.add_instr("if (!UNTAG_Bool({e})) \
{ /* or */")
1007 var e2 = v.compile_expr(n_expr2)
1008 v.add_assignment(e, e2)
1015 redef class AAndExpr
1016 redef meth compile_expr(v)
1018 var e = v.ensure_var(v.compile_expr(n_expr))
1019 v.add_instr("if (UNTAG_Bool({e})) \
{ /* and */")
1022 var e2 = v.compile_expr(n_expr2)
1023 v.add_assignment(e, e2)
1030 redef class ANotExpr
1031 redef meth compile_expr(v)
1033 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
1038 redef meth compile_expr(v)
1040 var e = v.compile_expr(n_expr)
1041 var e2 = v.compile_expr(n_expr2)
1042 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
1046 redef class AIsaExpr
1047 redef meth compile_expr(v)
1049 var e = v.compile_expr(n_expr)
1050 return n_type.stype.compile_cast(v, e)
1054 redef class AAsCastExpr
1055 redef meth compile_expr(v)
1057 var e = v.compile_expr(n_expr)
1058 n_type.stype.compile_type_check(v, e, self)
1063 redef class ATrueExpr
1064 redef meth compile_expr(v)
1066 return " TAG_Bool(true)"
1070 redef class AFalseExpr
1071 redef meth compile_expr(v)
1073 return " TAG_Bool(false)"
1077 redef class AIntExpr
1078 redef meth compile_expr(v)
1080 return " TAG_Int({n_number.text})"
1084 redef class AFloatExpr
1085 redef meth compile_expr(v)
1087 return "BOX_Float({n_float.text})"
1091 redef class ACharExpr
1092 redef meth compile_expr(v)
1094 return " TAG_Char({n_char.text})"
1098 redef class AStringFormExpr
1099 redef meth compile_expr(v)
1101 var prop = stype.local_class.select_method(once "with_native
".to_symbol)
1103 return prop.compile_constructor_call(v, stype , ["BOX_NativeString(\
"{_cstring}\")", "TAG_Int({_cstring_length})"])
1106 # The raw string value
1107 protected meth string_text: String is abstract
1109 # The string in a C native format
1110 protected attr _cstring: String
1112 # The string length in bytes
1113 protected attr _cstring_length: Int
1115 # Compute _cstring and _cstring_length using string_text
1116 protected meth compute_string_info
1119 var str = string_text
1120 var res = new String
1122 while i < str.length do
1127 if c2 != '{' and c2 != '}' then
1137 _cstring_length = len
1141 redef class AStringExpr
1142 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1144 redef class AStartStringExpr
1145 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1147 redef class AMidStringExpr
1148 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1150 redef class AEndStringExpr
1151 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1154 redef class ASuperstringExpr
1155 redef meth compile_expr(v)
1157 var prop = stype.local_class.select_method(once "init".to_symbol)
1158 var recv = prop.compile_constructor_call(v, stype, new Array[String])
1160 var prop2 = stype.local_class.select_method(once "append
".to_symbol)
1162 var prop3 = stype.local_class.select_method(once "to_s
".to_symbol)
1163 for ne in n_exprs do
1164 var e = v.ensure_var(v.compile_expr(ne))
1165 if ne.stype != stype then
1166 v.add_assignment(e, prop3.compile_call(v, [e]))
1168 prop2.compile_call(v, [recv, e])
1175 redef class ANullExpr
1176 redef meth compile_expr(v)
1178 return " NIT_NULL /*null*/"
1182 redef class AArrayExpr
1183 redef meth compile_expr(v)
1185 var prop = stype.local_class.select_method(once "with_capacity
".to_symbol)
1186 var recv = prop.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1188 var prop2 = stype.local_class.select_method(once "add
".to_symbol)
1189 for ne in n_exprs do
1190 var e = v.compile_expr(ne)
1191 prop2.compile_call(v, [recv, e])
1197 redef class ARangeExpr
1198 redef meth compile_expr(v)
1200 var prop = stype.local_class.select_method(propname)
1201 var e = v.compile_expr(n_expr)
1202 var e2 = v.compile_expr(n_expr2)
1203 return prop.compile_constructor_call(v, stype, [e, e2])
1205 # The constructor that must be used for the range
1206 protected meth propname: Symbol is abstract
1209 redef class ACrangeExpr
1210 redef meth propname do return once "init".to_symbol
1212 redef class AOrangeExpr
1213 redef meth propname do return once "without_last
".to_symbol
1216 redef class ASuperExpr
1217 redef meth compile_stmt(v)
1219 var e = compile_expr(v)
1220 if e != null then v.add_instr("{e};")
1223 redef meth compile_expr(v)
1225 var arity = v.nmc.method_params.length - 1
1226 if init_in_superclass != null then
1227 arity = init_in_superclass.signature.arity
1229 var args = new Array[String].with_capacity(arity + 1)
1230 args.add(v.nmc.method_params[0])
1231 if n_args.length != arity then
1232 for i in [0..arity[ do
1233 args.add(v.nmc.method_params[i + 1])
1237 args.add(v.compile_expr(na))
1240 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1241 if init_in_superclass != null then
1242 return init_in_superclass.compile_call(v, args)
1244 if prop.global.is_init then args.add("init_table
")
1245 return prop.compile_super_call(v, args)
1250 redef class AAttrExpr
1251 redef meth compile_expr(v)
1253 var e = v.compile_expr(n_expr)
1254 return prop.compile_access(v, e)
1258 redef class AAttrAssignExpr
1259 redef meth compile_stmt(v)
1261 var e = v.compile_expr(n_expr)
1262 var e2 = v.compile_expr(n_value)
1263 v.add_assignment(prop.compile_access(v, e), e2)
1266 redef class AAttrReassignExpr
1267 redef meth compile_stmt(v)
1269 var e1 = v.compile_expr(n_expr)
1270 var e2 = prop.compile_access(v, e1)
1271 var e3 = v.compile_expr(n_value)
1272 var e4 = assign_method.compile_call(v, [e2, e3])
1273 v.add_assignment(e2, e4)
1277 redef class ASendExpr
1278 redef meth compile_expr(v)
1280 var recv = v.compile_expr(n_expr)
1281 var cargs = new Array[String]
1283 for a in arguments do
1284 cargs.add(v.compile_expr(a))
1287 var e = prop.compile_call(v, cargs)
1288 if prop.global.is_init then
1289 v.invoke_super_init_calls_after(prop)
1294 redef meth compile_stmt(v)
1296 var e = compile_expr(v)
1298 v.add_instr(e + ";")
1303 redef class ASendReassignExpr
1304 redef meth compile_expr(v)
1306 var recv = v.compile_expr(n_expr)
1307 var cargs = new Array[String]
1309 for a in arguments do
1310 cargs.add(v.compile_expr(a))
1313 var e2 = read_prop.compile_call(v, cargs)
1314 var e3 = v.compile_expr(n_value)
1315 var e4 = assign_method.compile_call(v, [e2, e3])
1317 return prop.compile_call(v, cargs)
1321 redef class ANewExpr
1322 redef meth compile_expr(v)
1324 var cargs = new Array[String]
1325 for a in arguments do
1326 cargs.add(v.compile_expr(a))
1328 return prop.compile_constructor_call(v, stype, cargs)
1332 redef class AProxyExpr
1333 redef meth compile_expr(v)
1335 return v.compile_expr(n_expr)
1339 redef class AOnceExpr
1340 redef meth compile_expr(v)
1342 var i = v.new_number
1343 var cvar = v.cfc.get_var
1344 v.add_decl("static val_t once_value_
{i}; static int once_bool_
{i}; /* Once value
for {cvar}*/")
1345 v.add_instr("if (once_bool_
{i}) {cvar} = once_value_
{i};")
1346 v.add_instr("else \
{")
1348 v.cfc.free_var(cvar)
1349 var e = v.compile_expr(n_expr)
1350 v.add_assignment(cvar, e)
1351 v.add_instr("once_value_
{i} = {cvar};")
1352 v.add_instr("once_bool_
{i} = true;")