Make that generated files are path independent.
[nit.git] / src / compiling / compiling_methods.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Compile method bodies, statments and expressions to C.
18 package compiling_methods
19
20 import compiling_base
21 private import syntax
22
23 redef class CompilerVisitor
24 # Compile a statment node
25 meth compile_stmt(n: PExpr)
26 do
27 n.prepare_compile_stmt(self)
28 var i = _variable_index
29 n.compile_stmt(self)
30 _variable_index = i
31 end
32
33 # Compile is expression node
34 meth compile_expr(n: PExpr): String
35 do
36 var i = _variable_index
37 var s = n.compile_expr(self)
38 _variable_index = i
39 if s[0] == ' ' then
40 return s
41 end
42 if s == variable(_variable_index-1) then
43 return s
44 end
45 var v = get_var
46 add_assignment(v, s)
47 return v
48 end
49
50 # Ensure that a c expression is a var
51 meth ensure_var(s: String): String
52 do
53 if s.substring(0,3) == "variable" then
54 return s
55 end
56 var v = get_var
57 add_assignment(v, s)
58 return v
59 end
60
61 # Add a assignment between a variable and an expression
62 meth add_assignment(v: String, s: String)
63 do
64 if v != s then
65 add_instr("{v} = {s};")
66 end
67 end
68
69 # Return the ith variable
70 protected meth variable(i: Int): String
71 do
72 return "variable{i}"
73 end
74
75 # Next available variable number
76 attr _variable_index: Int
77
78 # Total number of variable
79 attr _variable_index_max: Int
80
81 # Return the next available variable
82 meth get_var: String
83 do
84 var v = variable(_variable_index)
85 _variable_index = _variable_index + 1
86 if _variable_index > _variable_index_max then
87 add_decl("val_t {v};")
88 _variable_index_max = _variable_index
89 end
90 return v
91 end
92
93 # Mark the variable available
94 meth free_var(v: String)
95 do
96 # FIXME: So ugly..
97 if v == variable(_variable_index-1) then
98 _variable_index = _variable_index - 1
99 end
100 end
101
102 # Clear all status related to a method body
103 meth clear
104 do
105 _has_return = false
106 indent_level = 0
107 _variable_index = 0
108 _variable_index_max = 0
109 end
110
111 # Association between nit variable and the corrsponding c variable
112 readable attr _varnames: Map[Variable, String] = new HashMap[Variable, String]
113
114 # Is a "return" found in the method body
115 readable writable attr _has_return: Bool
116
117 # Association between parameters and the corresponding c variables
118 readable writable attr _method_params: Array[String]
119
120 # Current method compiled
121 readable writable attr _method: MMSrcMethod
122
123 # Where a nit return must branch
124 readable writable attr _return_label: String
125
126 # Where a nit break must branch
127 readable writable attr _break_label: String
128
129 # Where a nit continue must branch
130 readable writable attr _continue_label: String
131
132 # Variable where a functionnal nit return must store its value
133 readable writable attr _return_value: String
134
135 # Generate an fprintf to display an error location
136 meth printf_locate_error(node: PNode): String
137 do
138 var s = "fprintf(stderr, \""
139 if method != null then s.append(" in %s")
140 s.append(" (%s:%d)\\n\", ")
141 if method != null then s.append("LOCATE_{method.cname}, ")
142 s.append("LOCATE_{module.name}, {node.line_number});")
143 return s
144 end
145
146 redef init(module: MMSrcModule)
147 do
148 super
149 clear
150 end
151
152 meth invoke_super_init_calls_after(start_prop: MMMethod)
153 do
154 var n = method.node
155 assert n isa AConcreteInitPropdef
156
157 if n.super_init_calls.is_empty then return
158 var i = 0
159 var j = 0
160 #var s = ""
161 if start_prop != null then
162 while n.super_init_calls[i] != start_prop do
163 #s.append(" {n.super_init_calls[i]}")
164 i += 1
165 end
166 i += 1
167 #s.append(" {start_prop}")
168
169 while n.explicit_super_init_calls[j] != start_prop do
170 j += 1
171 end
172 j += 1
173 end
174 var stop_prop: MMMethod = null
175 if j < n.explicit_super_init_calls.length then
176 stop_prop = n.explicit_super_init_calls[j]
177 end
178 var l = n.super_init_calls.length
179 #s.append(" [")
180 while i < l do
181 var p = n.super_init_calls[i]
182 if p == stop_prop then break
183 var cargs = method_params
184 if p.signature.arity == 0 then
185 cargs = [method_params[0]]
186 end
187 #s.append(" {p}")
188 p.compile_call(self, cargs)
189 i += 1
190 end
191 #s.append(" ]")
192 #while i < l do
193 # s.append(" {n.super_init_calls[i]}")
194 # i += 1
195 #end
196 #if stop_prop != null then s.append(" (stop at {stop_prop})")
197 #n.printl("implicit calls in {n.method}: {s}")
198 end
199 end
200
201 ###############################################################################
202
203 redef class MMMethod
204 # Compile a call on self for given arguments
205 # Most calls are compiled with a table access,
206 # primitive calles are inlined
207 # == and != are guarded and possibly inlined
208 meth compile_call(v: CompilerVisitor, cargs: Array[String]): String
209 do
210 var i = self
211 assert i isa MMSrcMethod
212 if i.node isa AInternMethPropdef or
213 (i.local_class.name == (once "Array".to_symbol) and name == (once "[]".to_symbol))
214 then
215 var e = i.do_compile_inside(v, cargs)
216 return e
217 end
218 var ee = once "==".to_symbol
219 var ne = once "!=".to_symbol
220 if name == ne then
221 var eqp = signature.recv.local_class.select_method(ee)
222 var eqcall = eqp.compile_call(v, cargs)
223 return "TAG_Bool(!UNTAG_Bool({eqcall}))"
224 end
225 if global.is_init then
226 cargs = cargs.to_a
227 cargs.add("init_table /*YYY*/")
228 end
229
230 var m = "(({cname}_t)CALL({cargs[0]},{global.color_id}))"
231 var vcall = "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
232 if name == ee then
233 vcall = "UNTAG_Bool({vcall})"
234 var obj = once "Object".to_symbol
235 if i.local_class.name == obj then
236 vcall = "(({m}=={i.cname})?(IS_EQUAL_NN({cargs[0]},{cargs[1]})):({vcall}))"
237 end
238 vcall = "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
239 end
240 if signature.return_type != null then
241 return vcall
242 else
243 v.add_instr(vcall + ";")
244 return null
245 end
246 end
247
248 # Compile a call as constructor with given args
249 meth compile_constructor_call(v: CompilerVisitor, cargs: Array[String]): String
250 do
251 var recv = v.get_var
252 var stype = signature.recv
253 v.add_instr("{recv} = NEW_{global.intro.cname}({cargs.join(", ")}); /*new {stype}*/")
254 return recv
255 end
256
257 # Compile a call as call-next-method on self with given args
258 meth compile_super_call(v: CompilerVisitor, cargs: Array[String]): String
259 do
260 var m = "(({cname}_t)CALL({cargs[0]},{color_id_for_super}))"
261 var vcall = "{m}({cargs.join(", ")}) /*super {local_class}::{name}*/"
262 return vcall
263 end
264 end
265
266 redef class MMAttribute
267 # Compile an acces on selffor a given reciever.
268 # Result is a valid C left-value for assigment
269 meth compile_access(v: CompilerVisitor, recv: String): String
270 do
271 return "{global.attr_access}({recv}) /*{local_class}::{name}*/"
272 end
273 end
274
275 redef class MMLocalProperty
276 # Compile the property as a C property
277 meth compile_property_to_c(v: CompilerVisitor) do end
278 end
279
280 redef class MMSrcMethod
281 # Compile and declare the signature to C
282 protected meth decl_csignature(v: CompilerVisitor, args: Array[String]): String
283 do
284 var params = new Array[String]
285 var params_new: Array[String] = null
286 if global.is_init then
287 params_new = new Array[String]
288 end
289 params.add("val_t {args[0]}")
290 for i in [0..signature.arity[ do
291 var p = "val_t {args[i+1]}"
292 params.add(p)
293 if params_new != null then params_new.add(p)
294 end
295 if global.is_init then
296 params.add("int* init_table")
297 end
298 var ret: String
299 if signature.return_type != null then
300 ret = "val_t"
301 else
302 ret = "void"
303 end
304 var p = params.join(", ")
305 var s = "{ret} {cname}({p})"
306 v.add_decl("typedef {ret} (* {cname}_t)({p});")
307 v.add_decl(s + ";")
308 if params_new != null then
309 v.add_decl("val_t NEW_{cname}({params_new.join(", ")});")
310 end
311 return s
312 end
313
314 redef meth compile_property_to_c(v)
315 do
316 v.clear
317 var args = new Array[String]
318 args.add(" self")
319 for i in [0..signature.arity[ do
320 args.add(" param{i}")
321 end
322 var cs = decl_csignature(v, args)
323 v.add_decl("#define LOCATE_{cname} \"{full_name}\"")
324
325 v.add_instr("{cs} \{")
326 v.indent
327 var ctx_old = v.ctx
328 v.ctx = new CContext
329
330 v.add_decl("struct trace_t trace = \{NULL, NULL, {node.line_number}, LOCATE_{cname}};")
331 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
332 v.add_instr("trace.file = LOCATE_{module.name};")
333 var s = do_compile_inside(v, args)
334 v.add_instr("tracehead = trace.prev;")
335 if s == null then
336 v.add_instr("return;")
337 else
338 v.add_instr("return {s};")
339 end
340
341 ctx_old.append(v.ctx)
342 v.ctx = ctx_old
343 v.unindent
344 v.add_instr("}")
345 end
346
347 # Compile the method body inline
348 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
349 end
350
351 redef class MMReadImplementationMethod
352 redef meth do_compile_inside(v, params)
353 do
354 return node.prop.compile_access(v, params[0])
355 end
356 end
357
358 redef class MMWriteImplementationMethod
359 redef meth do_compile_inside(v, params)
360 do
361 v.add_assignment(node.prop.compile_access(v, params[0]), params[1])
362 return null
363 end
364 end
365
366 redef class MMMethSrcMethod
367 redef meth do_compile_inside(v, params)
368 do
369 return node.do_compile_inside(v, self, params)
370 end
371 end
372
373 redef class MMType
374 # Compile a subtype check to self
375 # Return a NIT Bool
376 meth compile_cast(v: CompilerVisitor, recv: String): String
377 do
378 # Fixme: handle formaltypes
379 var g = local_class.global
380 return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
381 end
382
383 # Compile a cast assertion
384 meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode)
385 do
386 # Fixme: handle formaltypes
387 var g = local_class.global
388 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}*/;")
389 end
390 end
391
392 ###############################################################################
393
394 redef class AMethPropdef
395 # Compile the method body
396 meth do_compile_inside(v: CompilerVisitor, method: MMSrcMethod, params: Array[String]): String is abstract
397 end
398
399 redef class AConcreteMethPropdef
400 redef meth do_compile_inside(v, method, params)
401 do
402 var orig_meth: MMLocalProperty = method.global.intro
403 var orig_sig = orig_meth.signature_for(method.signature.recv)
404 if n_signature != null then
405 var sig = n_signature
406 assert sig isa ASignature
407 for ap in sig.n_params do
408 var cname = v.get_var
409 v.varnames[ap.variable] = cname
410 var orig_type = orig_sig[ap.position]
411 if not orig_type < ap.variable.stype then
412 # FIXME: do not test always
413 # FIXME: handle formal types
414 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
415 ap.variable.stype.compile_type_check(v, params[ap.position + 1], ap)
416 end
417 v.add_assignment(cname, params[ap.position + 1])
418 end
419 end
420 var old_method_params = v.method_params
421 var old_return_label = v.return_label
422 var old_return_value = v.return_value
423 var old_has_return = v.has_return
424
425 var itpos: String = null
426 if self isa AConcreteInitPropdef then
427 itpos = "VAL2OBJ({params[0]})->vft[{method.local_class.global.init_table_pos_id}].i"
428 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
429 v.add_instr("if (init_table[{itpos}]) return;")
430 end
431
432 v.method_params = params
433 v.has_return = false
434 v.return_label = "return_label{v.new_number}"
435 if method.signature.return_type != null then
436 v.return_value = v.get_var
437 v.free_var(v.return_value)
438 else
439 v.return_value = null
440 end
441 v.method = method
442 if self isa AConcreteInitPropdef then
443 v.invoke_super_init_calls_after(null)
444 end
445 if n_block != null then
446 v.compile_stmt(n_block)
447 end
448 if v.has_return then
449 v.add_instr("{v.return_label}: while(false);")
450 end
451 if self isa AConcreteInitPropdef then
452 v.add_instr("init_table[{itpos}] = 1;")
453 end
454 var ret = v.return_value
455 v.method_params = old_method_params
456 v.return_label = old_return_label
457 v.return_value = old_return_value
458 v.has_return = old_has_return
459 return ret
460 end
461 end
462
463 redef class ADeferredMethPropdef
464 redef meth do_compile_inside(v, method, params)
465 do
466 v.add_instr("fprintf(stderr, \"Deferred method %s called\");")
467 v.add_instr(v.printf_locate_error(self))
468 v.add_instr("nit_exit(1);")
469 if method.signature.return_type != null then
470 return("NIT_NULL")
471 else
472 return null
473 end
474 end
475 end
476
477 redef class AExternMethPropdef
478 redef meth do_compile_inside(v, method, params)
479 do
480 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
481 if n_extern != null then
482 ename = n_extern.text
483 ename = ename.substring(1, ename.length-2)
484 end
485 var sig = method.signature
486 if params.length != sig.arity + 1 then
487 printl("par:{params.length} sig:{sig.arity}")
488 end
489 var args = new Array[String]
490 args.add(sig.recv.unboxtype(params[0]))
491 for i in [0..sig.arity[ do
492 args.add(sig[i].unboxtype(params[i+1]))
493 end
494 var s = "{ename}({args.join(", ")})"
495 if sig.return_type != null then
496 return sig.return_type.boxtype(s)
497 else
498 v.add_instr("{s};")
499 return null
500 end
501 end
502 end
503
504 redef class AInternMethPropdef
505 redef meth do_compile_inside(v, method, p)
506 do
507 var c = method.local_class.name
508 var n = method.name
509 var s: String = null
510 if c == once "Int".to_symbol then
511 if n == once "object_id".to_symbol then
512 s = "{p[0]}"
513 else if n == once "unary -".to_symbol then
514 s = "TAG_Int(-UNTAG_Int({p[0]}))"
515 else if n == once "output".to_symbol then
516 v.add_instr("printf(\"%d\\n\", UNTAG_Int({p[0]}));")
517 else if n == once "ascii".to_symbol then
518 s = "TAG_Char(UNTAG_Int({p[0]}))"
519 else if n == once "succ".to_symbol then
520 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
521 else if n == once "prec".to_symbol then
522 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
523 else if n == once "to_f".to_symbol then
524 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
525 else if n == once "+".to_symbol then
526 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
527 else if n == once "-".to_symbol then
528 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
529 else if n == once "*".to_symbol then
530 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
531 else if n == once "/".to_symbol then
532 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
533 else if n == once "%".to_symbol then
534 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
535 else if n == once "<".to_symbol then
536 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
537 else if n == once ">".to_symbol then
538 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
539 else if n == once "<=".to_symbol then
540 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
541 else if n == once ">=".to_symbol then
542 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
543 else if n == once "lshift".to_symbol then
544 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
545 else if n == once "rshift".to_symbol then
546 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
547 else if n == once "==".to_symbol then
548 s = "TAG_Bool(({p[0]})==({p[1]}))"
549 else if n == once "!=".to_symbol then
550 s = "TAG_Bool(({p[0]})!=({p[1]}))"
551 end
552 else if c == once "Float".to_symbol then
553 if n == once "object_id".to_symbol then
554 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
555 else if n == once "unary -".to_symbol then
556 s = "BOX_Float(-UNBOX_Float({p[0]}))"
557 else if n == once "output".to_symbol then
558 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
559 else if n == once "to_i".to_symbol then
560 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
561 else if n == once "+".to_symbol then
562 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
563 else if n == once "-".to_symbol then
564 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
565 else if n == once "*".to_symbol then
566 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
567 else if n == once "/".to_symbol then
568 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
569 else if n == once "<".to_symbol then
570 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
571 else if n == once ">".to_symbol then
572 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
573 else if n == once "<=".to_symbol then
574 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
575 else if n == once ">=".to_symbol then
576 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
577 end
578 else if c == once "Char".to_symbol then
579 if n == once "object_id".to_symbol then
580 s = "TAG_Int(UNTAG_Char({p[0]}))"
581 else if n == once "unary -".to_symbol then
582 s = "TAG_Char(-UNTAG_Char({p[0]}))"
583 else if n == once "output".to_symbol then
584 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
585 else if n == once "ascii".to_symbol then
586 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
587 else if n == once "succ".to_symbol then
588 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
589 else if n == once "prec".to_symbol then
590 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
591 else if n == once "to_i".to_symbol then
592 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
593 else if n == once "+".to_symbol then
594 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
595 else if n == once "-".to_symbol then
596 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
597 else if n == once "*".to_symbol then
598 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
599 else if n == once "/".to_symbol then
600 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
601 else if n == once "%".to_symbol then
602 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
603 else if n == once "<".to_symbol then
604 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
605 else if n == once ">".to_symbol then
606 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
607 else if n == once "<=".to_symbol then
608 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
609 else if n == once ">=".to_symbol then
610 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
611 else if n == once "==".to_symbol then
612 s = "TAG_Bool(({p[0]})==({p[1]}))"
613 else if n == once "!=".to_symbol then
614 s = "TAG_Bool(({p[0]})!=({p[1]}))"
615 end
616 else if c == once "Bool".to_symbol then
617 if n == once "object_id".to_symbol then
618 s = "TAG_Int(UNTAG_Bool({p[0]}))"
619 else if n == once "unary -".to_symbol then
620 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
621 else if n == once "output".to_symbol then
622 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
623 else if n == once "ascii".to_symbol then
624 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
625 else if n == once "to_i".to_symbol then
626 s = "TAG_Int(UNTAG_Bool({p[0]}))"
627 else if n == once "==".to_symbol then
628 s = "TAG_Bool(({p[0]})==({p[1]}))"
629 else if n == once "!=".to_symbol then
630 s = "TAG_Bool(({p[0]})!=({p[1]}))"
631 end
632 else if c == once "NativeArray".to_symbol then
633 if n == once "object_id".to_symbol then
634 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
635 else if n == once "[]".to_symbol then
636 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
637 else if n == once "[]=".to_symbol then
638 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
639 else if n == once "copy_to".to_symbol then
640 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
641 end
642 else if c == once "NativeString".to_symbol then
643 if n == once "object_id".to_symbol then
644 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
645 else if n == once "atoi".to_symbol then
646 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
647 else if n == once "[]".to_symbol then
648 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
649 else if n == once "[]=".to_symbol then
650 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
651 else if n == once "copy_to".to_symbol then
652 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]}));")
653 end
654 else if n == once "object_id".to_symbol then
655 s = "TAG_Int((bigint){p[0]})"
656 else if n == once "sys".to_symbol then
657 s = "(G_sys)"
658 else if n == once "is_same_type".to_symbol then
659 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
660 else if n == once "exit".to_symbol then
661 v.add_instr("exit(UNTAG_Int({p[1]}));")
662 else if n == once "calloc_array".to_symbol then
663 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
664 else if n == once "calloc_string".to_symbol then
665 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
666
667 else
668 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
669 end
670 if method.signature.return_type != null and s == null then
671 s = "NIT_NULL /*stub*/"
672 end
673 return s
674 end
675 end
676
677 ###############################################################################
678
679 redef class PExpr
680 # Compile the node as an expression
681 # Only the visitor should call it
682 meth compile_expr(v: CompilerVisitor): String is abstract
683
684 # Prepare a call of node as a statement
685 # Only the visitor should call it
686 # It's used for local variable managment
687 meth prepare_compile_stmt(v: CompilerVisitor) do end
688
689 # Compile the node as a statement
690 # Only the visitor should call it
691 meth compile_stmt(v: CompilerVisitor) do printl("Error!")
692 end
693
694 redef class ABlockExpr
695 redef meth compile_stmt(v)
696 do
697 for n in n_expr do
698 v.compile_stmt(n)
699 end
700 end
701 end
702
703 redef class AVardeclExpr
704 redef meth prepare_compile_stmt(v)
705 do
706 var cname = v.get_var
707 v.varnames[variable] = cname
708 end
709
710 redef meth compile_stmt(v)
711 do
712 var cname = v.varnames[variable]
713 if n_expr == null then
714 var t = variable.stype
715 v.add_assignment(cname, "{t.default_cvalue} /*decl variable {variable.name}*/")
716 else
717 var e = v.compile_expr(n_expr)
718 v.add_assignment(cname, e)
719 end
720 end
721 end
722
723 redef class AReturnExpr
724 redef meth compile_stmt(v)
725 do
726 v.has_return = true
727 if n_expr != null then
728 var e = v.compile_expr(n_expr)
729 v.add_assignment(v.return_value, e)
730 end
731 v.add_instr("goto {v.return_label};")
732 end
733 end
734
735 redef class ABreakExpr
736 redef meth compile_stmt(v)
737 do
738 v.add_instr("goto {v.break_label};")
739 end
740 end
741
742 redef class AContinueExpr
743 redef meth compile_stmt(v)
744 do
745 v.add_instr("goto {v.continue_label};")
746 end
747 end
748
749 redef class AAbortExpr
750 redef meth compile_stmt(v)
751 do
752 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
753 end
754 end
755
756 redef class ADoExpr
757 redef meth compile_stmt(v)
758 do
759 if n_block != null then
760 v.compile_stmt(n_block)
761 end
762 end
763 end
764
765 redef class AIfExpr
766 redef meth compile_stmt(v)
767 do
768 var e = v.compile_expr(n_expr)
769 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
770 v.free_var(e)
771 if n_then != null then
772 v.indent
773 v.compile_stmt(n_then)
774 v.unindent
775 end
776 if n_else != null then
777 v.add_instr("} else \{ /*if*/")
778 v.indent
779 v.compile_stmt(n_else)
780 v.unindent
781 end
782 v.add_instr("}")
783 end
784 end
785
786 redef class AIfexprExpr
787 redef meth compile_expr(v)
788 do
789 var e = v.compile_expr(n_expr)
790 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
791 v.free_var(e)
792 v.indent
793 var e = v.ensure_var(v.compile_expr(n_then))
794 v.unindent
795 v.add_instr("} else \{ /*if*/")
796 v.free_var(e)
797 v.indent
798 var e2 = v.ensure_var(v.compile_expr(n_else))
799 v.add_assignment(e, e2)
800 v.unindent
801 v.add_instr("}")
802 return e
803 end
804 end
805
806 redef class AControlableBlock
807 meth compile_inside_block(v: CompilerVisitor) is abstract
808 redef meth compile_stmt(v)
809 do
810 var old_break_label = v.break_label
811 var old_continue_label = v.continue_label
812 var id = v.new_number
813 v.break_label = "break_{id}"
814 v.continue_label = "continue_{id}"
815
816 compile_inside_block(v)
817
818
819 v.break_label = old_break_label
820 v.continue_label = old_continue_label
821 end
822 end
823
824 redef class AWhileExpr
825 redef meth compile_inside_block(v)
826 do
827 v.add_instr("while (true) \{ /*while*/")
828 v.indent
829 var e = v.compile_expr(n_expr)
830 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
831 v.free_var(e)
832 if n_block != null then
833 v.compile_stmt(n_block)
834 end
835 v.add_instr("{v.continue_label}: while(0);")
836 v.unindent
837 v.add_instr("}")
838 v.add_instr("{v.break_label}: while(0);")
839 end
840 end
841
842 redef class AForExpr
843 redef meth compile_inside_block(v)
844 do
845 v.compile_stmt(n_vardecl)
846 end
847 end
848
849 redef class AForVardeclExpr
850 redef meth compile_stmt(v)
851 do
852 var e = v.compile_expr(n_expr)
853 var prop = n_expr.stype.local_class.select_method(once "iterator".to_symbol)
854 if prop == null then
855 printl("No iterator")
856 return
857 end
858 var ittype = prop.signature.return_type
859 v.free_var(e)
860 var iter = v.get_var
861 v.add_assignment(iter, prop.compile_call(v, [e]))
862 var prop2 = ittype.local_class.select_method(once "is_ok".to_symbol)
863 if prop2 == null then
864 printl("No is_ok")
865 return
866 end
867 var prop3 = ittype.local_class.select_method(once "item".to_symbol)
868 if prop3 == null then
869 printl("No item")
870 return
871 end
872 var prop4 = ittype.local_class.select_method(once "next".to_symbol)
873 if prop4 == null then
874 printl("No next")
875 return
876 end
877 v.add_instr("while (true) \{ /*for*/")
878 v.indent
879 var ok = v.get_var
880 v.add_assignment(ok, prop2.compile_call(v, [iter]))
881 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
882 v.free_var(ok)
883 var e = prop3.compile_call(v, [iter])
884 e = v.ensure_var(e)
885 v.varnames[variable] = e
886 var par = parent
887 assert par isa AForExpr
888 var n_block = par.n_block
889 if n_block != null then
890 v.compile_stmt(n_block)
891 end
892 v.add_instr("{v.continue_label}: while(0);")
893 e = prop4.compile_call(v, [iter])
894 assert e == null
895 v.unindent
896 v.add_instr("}")
897 v.add_instr("{v.break_label}: while(0);")
898 end
899 end
900
901 redef class AAssertExpr
902 redef meth compile_stmt(v)
903 do
904 var e = v.compile_expr(n_expr)
905 var s = ""
906 if n_id != null then
907 s = " '{n_id.text}' "
908 end
909 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
910 end
911 end
912
913 redef class AVarExpr
914 redef meth compile_expr(v)
915 do
916 return " {v.varnames[variable]} /*{variable.name}*/"
917 end
918 end
919
920 redef class AVarAssignExpr
921 redef meth compile_stmt(v)
922 do
923 var e = v.compile_expr(n_value)
924 v.add_assignment(v.varnames[variable], "{e} /*{variable.name}=*/")
925 end
926 end
927
928 redef class AVarReassignExpr
929 redef meth compile_stmt(v)
930 do
931 var e1 = v.varnames[variable]
932 var e2 = v.compile_expr(n_value)
933 var e3 = assign_method.compile_call(v, [e1, e2])
934 v.add_assignment(v.varnames[variable], "{e3} /*{variable.name}*/")
935 end
936 end
937
938 redef class ASelfExpr
939 redef meth compile_expr(v)
940 do
941 return v.method_params[0]
942 end
943 end
944
945 redef class AOrExpr
946 redef meth compile_expr(v)
947 do
948 var e = v.ensure_var(v.compile_expr(n_expr))
949 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
950 v.free_var(e)
951 v.indent
952 var e2 = v.compile_expr(n_expr2)
953 v.add_assignment(e, e2)
954 v.unindent
955 v.add_instr("}")
956 return e
957 end
958 end
959
960 redef class AAndExpr
961 redef meth compile_expr(v)
962 do
963 var e = v.ensure_var(v.compile_expr(n_expr))
964 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
965 v.free_var(e)
966 v.indent
967 var e2 = v.compile_expr(n_expr2)
968 v.add_assignment(e, e2)
969 v.unindent
970 v.add_instr("}")
971 return e
972 end
973 end
974
975 redef class ANotExpr
976 redef meth compile_expr(v)
977 do
978 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
979 end
980 end
981
982 redef class AEeExpr
983 redef meth compile_expr(v)
984 do
985 var e = v.compile_expr(n_expr)
986 var e2 = v.compile_expr(n_expr2)
987 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
988 end
989 end
990
991 redef class AIsaExpr
992 redef meth compile_expr(v)
993 do
994 var e = v.compile_expr(n_expr)
995 return n_type.stype.compile_cast(v, e)
996 end
997 end
998
999 redef class AAsCastExpr
1000 redef meth compile_expr(v)
1001 do
1002 var e = v.compile_expr(n_expr)
1003 n_type.stype.compile_type_check(v, e, self)
1004 return e
1005 end
1006 end
1007
1008 redef class ATrueExpr
1009 redef meth compile_expr(v)
1010 do
1011 return " TAG_Bool(true)"
1012 end
1013 end
1014
1015 redef class AFalseExpr
1016 redef meth compile_expr(v)
1017 do
1018 return " TAG_Bool(false)"
1019 end
1020 end
1021
1022 redef class AIntExpr
1023 redef meth compile_expr(v)
1024 do
1025 return " TAG_Int({n_number.text})"
1026 end
1027 end
1028
1029 redef class AFloatExpr
1030 redef meth compile_expr(v)
1031 do
1032 return "BOX_Float({n_float.text})"
1033 end
1034 end
1035
1036 redef class ACharExpr
1037 redef meth compile_expr(v)
1038 do
1039 return " TAG_Char({n_char.text})"
1040 end
1041 end
1042
1043 redef class AStringFormExpr
1044 redef meth compile_expr(v)
1045 do
1046 var prop = stype.local_class.select_method(once "with_native".to_symbol)
1047 compute_string_info
1048 return prop.compile_constructor_call(v, ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1049 end
1050
1051 # The raw string value
1052 protected meth string_text: String is abstract
1053
1054 # The string in a C native format
1055 protected attr _cstring: String
1056
1057 # The string length in bytes
1058 protected attr _cstring_length: Int
1059
1060 # Compute _cstring and _cstring_length using string_text
1061 protected meth compute_string_info
1062 do
1063 var len = 0
1064 var str = string_text
1065 var res = new String
1066 var i = 0
1067 while i < str.length do
1068 var c = str[i]
1069 if c == '\\' then
1070 i = i + 1
1071 var c2 = str[i]
1072 if c2 != '{' and c2 != '}' then
1073 res.add(c)
1074 end
1075 c = c2
1076 end
1077 len = len + 1
1078 res.add(c)
1079 i = i + 1
1080 end
1081 _cstring = res
1082 _cstring_length = len
1083 end
1084 end
1085
1086 redef class AStringExpr
1087 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1088 end
1089 redef class AStartStringExpr
1090 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1091 end
1092 redef class AMidStringExpr
1093 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1094 end
1095 redef class AEndStringExpr
1096 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1097 end
1098
1099 redef class ASuperstringExpr
1100 redef meth compile_expr(v)
1101 do
1102 var prop = stype.local_class.select_method(once "init".to_symbol)
1103 var recv = prop.compile_constructor_call(v, new Array[String])
1104
1105 var prop2 = stype.local_class.select_method(once "append".to_symbol)
1106
1107 var prop3 = stype.local_class.select_method(once "to_s".to_symbol)
1108 for ne in n_exprs do
1109 var e = v.ensure_var(v.compile_expr(ne))
1110 if ne.stype != stype then
1111 v.add_assignment(e, prop3.compile_call(v, [e]))
1112 end
1113 prop2.compile_call(v, [recv, e])
1114 end
1115
1116 return recv
1117 end
1118 end
1119
1120 redef class ANullExpr
1121 redef meth compile_expr(v)
1122 do
1123 return " NIT_NULL /*null*/"
1124 end
1125 end
1126
1127 redef class AArrayExpr
1128 redef meth compile_expr(v)
1129 do
1130 var prop = stype.local_class.select_method(once "with_capacity".to_symbol)
1131 var recv = prop.compile_constructor_call(v,["TAG_Int({n_exprs.length})"])
1132
1133 var prop2 = stype.local_class.select_method(once "add".to_symbol)
1134 for ne in n_exprs do
1135 var e = v.compile_expr(ne)
1136 prop2.compile_call(v, [recv, e])
1137 end
1138 return recv
1139 end
1140 end
1141
1142 redef class ARangeExpr
1143 redef meth compile_expr(v)
1144 do
1145 var prop = stype.local_class.select_method(propname)
1146 var e = v.compile_expr(n_expr)
1147 var e2 = v.compile_expr(n_expr2)
1148 return prop.compile_constructor_call(v, [e, e2])
1149 end
1150 # The constructor that must be used for the range
1151 protected meth propname: Symbol is abstract
1152 end
1153
1154 redef class ACrangeExpr
1155 redef meth propname do return once "init".to_symbol
1156 end
1157 redef class AOrangeExpr
1158 redef meth propname do return once "without_last".to_symbol
1159 end
1160
1161 redef class ASuperExpr
1162 redef meth compile_stmt(v)
1163 do
1164 var e = compile_expr(v)
1165 if e != null then v.add_instr("{e};")
1166 end
1167
1168 redef meth compile_expr(v)
1169 do
1170 var arity = v.method_params.length - 1
1171 if init_in_superclass != null then
1172 arity = init_in_superclass.signature.arity
1173 end
1174 var args = new Array[String].with_capacity(arity + 1)
1175 args.add(v.method_params[0])
1176 if n_args.length != arity then
1177 for i in [0..arity[ do
1178 args.add(v.method_params[i + 1])
1179 end
1180 else
1181 for na in n_args do
1182 args.add(v.compile_expr(na))
1183 end
1184 end
1185 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1186 if init_in_superclass != null then
1187 return init_in_superclass.compile_call(v, args)
1188 else
1189 if prop.global.is_init then args.add("init_table")
1190 return prop.compile_super_call(v, args)
1191 end
1192 end
1193 end
1194
1195 redef class AAttrExpr
1196 redef meth compile_expr(v)
1197 do
1198 var e = v.compile_expr(n_expr)
1199 return prop.compile_access(v, e)
1200 end
1201 end
1202
1203 redef class AAttrAssignExpr
1204 redef meth compile_stmt(v)
1205 do
1206 var e = v.compile_expr(n_expr)
1207 var e2 = v.compile_expr(n_value)
1208 v.add_assignment(prop.compile_access(v, e), e2)
1209 end
1210 end
1211 redef class AAttrReassignExpr
1212 redef meth compile_stmt(v)
1213 do
1214 var e1 = v.compile_expr(n_expr)
1215 var e2 = prop.compile_access(v, e1)
1216 var e3 = v.compile_expr(n_value)
1217 var e4 = assign_method.compile_call(v, [e2, e3])
1218 v.add_assignment(e2, e4)
1219 end
1220 end
1221
1222 redef class ASendExpr
1223 redef meth compile_expr(v)
1224 do
1225 var recv = v.compile_expr(n_expr)
1226 var cargs = new Array[String]
1227 cargs.add(recv)
1228 for a in arguments do
1229 cargs.add(v.compile_expr(a))
1230 end
1231
1232 var e = prop.compile_call(v, cargs)
1233 if prop.global.is_init then
1234 v.invoke_super_init_calls_after(prop)
1235 end
1236 return e
1237 end
1238
1239 redef meth compile_stmt(v)
1240 do
1241 var e = compile_expr(v)
1242 if e != null then
1243 v.add_instr(e + ";")
1244 end
1245 end
1246 end
1247
1248 redef class ASendReassignExpr
1249 redef meth compile_expr(v)
1250 do
1251 var recv = v.compile_expr(n_expr)
1252 var cargs = new Array[String]
1253 cargs.add(recv)
1254 for a in arguments do
1255 cargs.add(v.compile_expr(a))
1256 end
1257
1258 var e2 = read_prop.compile_call(v, cargs)
1259 var e3 = v.compile_expr(n_value)
1260 var e4 = assign_method.compile_call(v, [e2, e3])
1261 cargs.add(e4)
1262 return prop.compile_call(v, cargs)
1263 end
1264 end
1265
1266 redef class ANewExpr
1267 redef meth compile_expr(v)
1268 do
1269 var cargs = new Array[String]
1270 for a in arguments do
1271 cargs.add(v.compile_expr(a))
1272 end
1273 return prop.compile_constructor_call(v, cargs)
1274 end
1275 end
1276
1277 redef class AProxyExpr
1278 redef meth compile_expr(v)
1279 do
1280 return v.compile_expr(n_expr)
1281 end
1282 end
1283
1284 redef class AOnceExpr
1285 redef meth compile_expr(v)
1286 do
1287 var i = v.new_number
1288 var cvar = v.get_var
1289 v.add_decl("static val_t once_value_{cvar}_{i}; static int once_bool_{cvar}_{i};")
1290 v.add_instr("if (once_bool_{cvar}_{i}) {cvar} = once_value_{cvar}_{i};")
1291 v.add_instr("else \{")
1292 v.indent
1293 v.free_var(cvar)
1294 var e = v.compile_expr(n_expr)
1295 v.add_assignment(cvar, e)
1296 v.add_instr("once_value_{cvar}_{i} = {cvar};")
1297 v.add_instr("once_bool_{cvar}_{i} = true;")
1298 v.unindent
1299 v.add_instr("}")
1300 return cvar
1301 end
1302 end