Methods without PNodes.
[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 if i isa MMSrcMethod then
212 if i isa MMMethSrcMethod and 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 end
219 var ee = once "==".to_symbol
220 var ne = once "!=".to_symbol
221 if name == ne then
222 var eqp = signature.recv.local_class.select_method(ee)
223 var eqcall = eqp.compile_call(v, cargs)
224 return "TAG_Bool(!UNTAG_Bool({eqcall}))"
225 end
226 if global.is_init then
227 cargs = cargs.to_a
228 cargs.add("init_table /*YYY*/")
229 end
230
231 var m = "(({cname}_t)CALL({cargs[0]},{global.color_id}))"
232 var vcall = "{m}({cargs.join(", ")}) /*{local_class}::{name}*/"
233 if name == ee then
234 vcall = "UNTAG_Bool({vcall})"
235 var obj = once "Object".to_symbol
236 if i.local_class.name == obj then
237 vcall = "(({m}=={i.cname})?(IS_EQUAL_NN({cargs[0]},{cargs[1]})):({vcall}))"
238 end
239 vcall = "TAG_Bool(({cargs.first} == {cargs[1]}) || (({cargs.first} != NIT_NULL) && {vcall}))"
240 end
241 if signature.return_type != null then
242 return vcall
243 else
244 v.add_instr(vcall + ";")
245 return null
246 end
247 end
248
249 # Compile a call as constructor with given args
250 meth compile_constructor_call(v: CompilerVisitor, recvtype: MMType, cargs: Array[String]): String
251 do
252 var recv = v.get_var
253 v.add_instr("{recv} = NEW_{recvtype.local_class}_{global.intro.cname}({cargs.join(", ")}); /*new {recvtype}*/")
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 var ln = 0
331 var s = self
332 if s.node != null then ln = s.node.line_number
333 v.add_decl("struct trace_t trace = \{NULL, NULL, {ln}, LOCATE_{cname}};")
334 v.add_instr("trace.prev = tracehead; tracehead = &trace;")
335 v.add_instr("trace.file = LOCATE_{module.name};")
336 var s = do_compile_inside(v, args)
337 v.add_instr("tracehead = trace.prev;")
338 if s == null then
339 v.add_instr("return;")
340 else
341 v.add_instr("return {s};")
342 end
343
344 ctx_old.append(v.ctx)
345 v.ctx = ctx_old
346 v.unindent
347 v.add_instr("}")
348 end
349
350 # Compile the method body inline
351 meth do_compile_inside(v: CompilerVisitor, params: Array[String]): String is abstract
352 end
353
354 redef class MMReadImplementationMethod
355 redef meth do_compile_inside(v, params)
356 do
357 return node.prop.compile_access(v, params[0])
358 end
359 end
360
361 redef class MMWriteImplementationMethod
362 redef meth do_compile_inside(v, params)
363 do
364 v.add_assignment(node.prop.compile_access(v, params[0]), params[1])
365 return null
366 end
367 end
368
369 redef class MMMethSrcMethod
370 redef meth do_compile_inside(v, params)
371 do
372 return node.do_compile_inside(v, self, params)
373 end
374 end
375
376 redef class MMType
377 # Compile a subtype check to self
378 # Return a NIT Bool
379 meth compile_cast(v: CompilerVisitor, recv: String): String
380 do
381 # Fixme: handle formaltypes
382 var g = local_class.global
383 return "TAG_Bool(({recv}==NIT_NULL) || VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {self}*/"
384 end
385
386 # Compile a cast assertion
387 meth compile_type_check(v: CompilerVisitor, recv: String, n: PNode)
388 do
389 # Fixme: handle formaltypes
390 var g = local_class.global
391 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}*/;")
392 end
393 end
394
395 ###############################################################################
396
397 redef class AMethPropdef
398 # Compile the method body
399 meth do_compile_inside(v: CompilerVisitor, method: MMSrcMethod, params: Array[String]): String is abstract
400 end
401
402 redef class AConcreteMethPropdef
403 redef meth do_compile_inside(v, method, params)
404 do
405 var orig_meth: MMLocalProperty = method.global.intro
406 var orig_sig = orig_meth.signature_for(method.signature.recv)
407 if n_signature != null then
408 var sig = n_signature
409 assert sig isa ASignature
410 for ap in sig.n_params do
411 var cname = v.get_var
412 v.varnames[ap.variable] = cname
413 var orig_type = orig_sig[ap.position]
414 if not orig_type < ap.variable.stype then
415 # FIXME: do not test always
416 # FIXME: handle formal types
417 v.add_instr("/* check if p<{ap.variable.stype} with p:{orig_type} */")
418 ap.variable.stype.compile_type_check(v, params[ap.position + 1], ap)
419 end
420 v.add_assignment(cname, params[ap.position + 1])
421 end
422 end
423 var old_method_params = v.method_params
424 var old_return_label = v.return_label
425 var old_return_value = v.return_value
426 var old_has_return = v.has_return
427
428 var itpos: String = null
429 if self isa AConcreteInitPropdef then
430 itpos = "VAL2OBJ({params[0]})->vft[{method.local_class.global.init_table_pos_id}].i"
431 # v.add_instr("printf(\"{method.full_name}: inittable[%d] = %d\\n\", {itpos}, init_table[{itpos}]);")
432 v.add_instr("if (init_table[{itpos}]) return;")
433 end
434
435 v.method_params = params
436 v.has_return = false
437 v.return_label = "return_label{v.new_number}"
438 if method.signature.return_type != null then
439 v.return_value = v.get_var
440 v.free_var(v.return_value)
441 else
442 v.return_value = null
443 end
444 v.method = method
445 if self isa AConcreteInitPropdef then
446 v.invoke_super_init_calls_after(null)
447 end
448 if n_block != null then
449 v.compile_stmt(n_block)
450 end
451 if v.has_return then
452 v.add_instr("{v.return_label}: while(false);")
453 end
454 if self isa AConcreteInitPropdef then
455 v.add_instr("init_table[{itpos}] = 1;")
456 end
457 var ret = v.return_value
458 v.method_params = old_method_params
459 v.return_label = old_return_label
460 v.return_value = old_return_value
461 v.has_return = old_has_return
462 return ret
463 end
464 end
465
466 redef class ADeferredMethPropdef
467 redef meth do_compile_inside(v, method, params)
468 do
469 v.add_instr("fprintf(stderr, \"Deferred method %s called\");")
470 v.add_instr(v.printf_locate_error(self))
471 v.add_instr("nit_exit(1);")
472 if method.signature.return_type != null then
473 return("NIT_NULL")
474 else
475 return null
476 end
477 end
478 end
479
480 redef class AExternMethPropdef
481 redef meth do_compile_inside(v, method, params)
482 do
483 var ename = "{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
484 if n_extern != null then
485 ename = n_extern.text
486 ename = ename.substring(1, ename.length-2)
487 end
488 var sig = method.signature
489 if params.length != sig.arity + 1 then
490 printl("par:{params.length} sig:{sig.arity}")
491 end
492 var args = new Array[String]
493 args.add(sig.recv.unboxtype(params[0]))
494 for i in [0..sig.arity[ do
495 args.add(sig[i].unboxtype(params[i+1]))
496 end
497 var s = "{ename}({args.join(", ")})"
498 if sig.return_type != null then
499 return sig.return_type.boxtype(s)
500 else
501 v.add_instr("{s};")
502 return null
503 end
504 end
505 end
506
507 redef class AInternMethPropdef
508 redef meth do_compile_inside(v, method, p)
509 do
510 var c = method.local_class.name
511 var n = method.name
512 var s: String = null
513 if c == once "Int".to_symbol then
514 if n == once "object_id".to_symbol then
515 s = "{p[0]}"
516 else if n == once "unary -".to_symbol then
517 s = "TAG_Int(-UNTAG_Int({p[0]}))"
518 else if n == once "output".to_symbol then
519 v.add_instr("printf(\"%d\\n\", UNTAG_Int({p[0]}));")
520 else if n == once "ascii".to_symbol then
521 s = "TAG_Char(UNTAG_Int({p[0]}))"
522 else if n == once "succ".to_symbol then
523 s = "TAG_Int(UNTAG_Int({p[0]})+1)"
524 else if n == once "prec".to_symbol then
525 s = "TAG_Int(UNTAG_Int({p[0]})-1)"
526 else if n == once "to_f".to_symbol then
527 s = "BOX_Float((float)UNTAG_Int({p[0]}))"
528 else if n == once "+".to_symbol then
529 s = "TAG_Int(UNTAG_Int({p[0]})+UNTAG_Int({p[1]}))"
530 else if n == once "-".to_symbol then
531 s = "TAG_Int(UNTAG_Int({p[0]})-UNTAG_Int({p[1]}))"
532 else if n == once "*".to_symbol then
533 s = "TAG_Int(UNTAG_Int({p[0]})*UNTAG_Int({p[1]}))"
534 else if n == once "/".to_symbol then
535 s = "TAG_Int(UNTAG_Int({p[0]})/UNTAG_Int({p[1]}))"
536 else if n == once "%".to_symbol then
537 s = "TAG_Int(UNTAG_Int({p[0]})%UNTAG_Int({p[1]}))"
538 else if n == once "<".to_symbol then
539 s = "TAG_Bool(UNTAG_Int({p[0]})<UNTAG_Int({p[1]}))"
540 else if n == once ">".to_symbol then
541 s = "TAG_Bool(UNTAG_Int({p[0]})>UNTAG_Int({p[1]}))"
542 else if n == once "<=".to_symbol then
543 s = "TAG_Bool(UNTAG_Int({p[0]})<=UNTAG_Int({p[1]}))"
544 else if n == once ">=".to_symbol then
545 s = "TAG_Bool(UNTAG_Int({p[0]})>=UNTAG_Int({p[1]}))"
546 else if n == once "lshift".to_symbol then
547 s = "TAG_Int(UNTAG_Int({p[0]})<<UNTAG_Int({p[1]}))"
548 else if n == once "rshift".to_symbol then
549 s = "TAG_Int(UNTAG_Int({p[0]})>>UNTAG_Int({p[1]}))"
550 else if n == once "==".to_symbol then
551 s = "TAG_Bool(({p[0]})==({p[1]}))"
552 else if n == once "!=".to_symbol then
553 s = "TAG_Bool(({p[0]})!=({p[1]}))"
554 end
555 else if c == once "Float".to_symbol then
556 if n == once "object_id".to_symbol then
557 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
558 else if n == once "unary -".to_symbol then
559 s = "BOX_Float(-UNBOX_Float({p[0]}))"
560 else if n == once "output".to_symbol then
561 v.add_instr("printf(\"%f\\n\", UNBOX_Float({p[0]}));")
562 else if n == once "to_i".to_symbol then
563 s = "TAG_Int((bigint)UNBOX_Float({p[0]}))"
564 else if n == once "+".to_symbol then
565 s = "BOX_Float(UNBOX_Float({p[0]})+UNBOX_Float({p[1]}))"
566 else if n == once "-".to_symbol then
567 s = "BOX_Float(UNBOX_Float({p[0]})-UNBOX_Float({p[1]}))"
568 else if n == once "*".to_symbol then
569 s = "BOX_Float(UNBOX_Float({p[0]})*UNBOX_Float({p[1]}))"
570 else if n == once "/".to_symbol then
571 s = "BOX_Float(UNBOX_Float({p[0]})/UNBOX_Float({p[1]}))"
572 else if n == once "<".to_symbol then
573 s = "TAG_Bool(UNBOX_Float({p[0]})<UNBOX_Float({p[1]}))"
574 else if n == once ">".to_symbol then
575 s = "TAG_Bool(UNBOX_Float({p[0]})>UNBOX_Float({p[1]}))"
576 else if n == once "<=".to_symbol then
577 s = "TAG_Bool(UNBOX_Float({p[0]})<=UNBOX_Float({p[1]}))"
578 else if n == once ">=".to_symbol then
579 s = "TAG_Bool(UNBOX_Float({p[0]})>=UNBOX_Float({p[1]}))"
580 end
581 else if c == once "Char".to_symbol then
582 if n == once "object_id".to_symbol then
583 s = "TAG_Int(UNTAG_Char({p[0]}))"
584 else if n == once "unary -".to_symbol then
585 s = "TAG_Char(-UNTAG_Char({p[0]}))"
586 else if n == once "output".to_symbol then
587 v.add_instr("printf(\"%c\", (unsigned char)UNTAG_Char({p[0]}));")
588 else if n == once "ascii".to_symbol then
589 s = "TAG_Int((unsigned char)UNTAG_Char({p[0]}))"
590 else if n == once "succ".to_symbol then
591 s = "TAG_Char(UNTAG_Char({p[0]})+1)"
592 else if n == once "prec".to_symbol then
593 s = "TAG_Char(UNTAG_Char({p[0]})-1)"
594 else if n == once "to_i".to_symbol then
595 s = "TAG_Int(UNTAG_Char({p[0]})-'0')"
596 else if n == once "+".to_symbol then
597 s = "TAG_Char(UNTAG_Char({p[0]})+UNTAG_Char({p[1]}))"
598 else if n == once "-".to_symbol then
599 s = "TAG_Char(UNTAG_Char({p[0]})-UNTAG_Char({p[1]}))"
600 else if n == once "*".to_symbol then
601 s = "TAG_Char(UNTAG_Char({p[0]})*UNTAG_Char({p[1]}))"
602 else if n == once "/".to_symbol then
603 s = "TAG_Char(UNTAG_Char({p[0]})/UNTAG_Char({p[1]}))"
604 else if n == once "%".to_symbol then
605 s = "TAG_Char(UNTAG_Char({p[0]})%UNTAG_Char({p[1]}))"
606 else if n == once "<".to_symbol then
607 s = "TAG_Bool(UNTAG_Char({p[0]})<UNTAG_Char({p[1]}))"
608 else if n == once ">".to_symbol then
609 s = "TAG_Bool(UNTAG_Char({p[0]})>UNTAG_Char({p[1]}))"
610 else if n == once "<=".to_symbol then
611 s = "TAG_Bool(UNTAG_Char({p[0]})<=UNTAG_Char({p[1]}))"
612 else if n == once ">=".to_symbol then
613 s = "TAG_Bool(UNTAG_Char({p[0]})>=UNTAG_Char({p[1]}))"
614 else if n == once "==".to_symbol then
615 s = "TAG_Bool(({p[0]})==({p[1]}))"
616 else if n == once "!=".to_symbol then
617 s = "TAG_Bool(({p[0]})!=({p[1]}))"
618 end
619 else if c == once "Bool".to_symbol then
620 if n == once "object_id".to_symbol then
621 s = "TAG_Int(UNTAG_Bool({p[0]}))"
622 else if n == once "unary -".to_symbol then
623 s = "TAG_Bool(-UNTAG_Bool({p[0]}))"
624 else if n == once "output".to_symbol then
625 v.add_instr("(void)printf(UNTAG_Bool({p[0]})?\"true\\n\":\"false\\n\");")
626 else if n == once "ascii".to_symbol then
627 s = "TAG_Bool(UNTAG_Bool({p[0]}))"
628 else if n == once "to_i".to_symbol then
629 s = "TAG_Int(UNTAG_Bool({p[0]}))"
630 else if n == once "==".to_symbol then
631 s = "TAG_Bool(({p[0]})==({p[1]}))"
632 else if n == once "!=".to_symbol then
633 s = "TAG_Bool(({p[0]})!=({p[1]}))"
634 end
635 else if c == once "NativeArray".to_symbol then
636 if n == once "object_id".to_symbol then
637 s = "TAG_Int(UNBOX_NativeArray({p[0]}))"
638 else if n == once "[]".to_symbol then
639 s = "UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]"
640 else if n == once "[]=".to_symbol then
641 v.add_instr("UNBOX_NativeArray({p[0]})[UNTAG_Int({p[1]})]={p[2]};")
642 else if n == once "copy_to".to_symbol then
643 v.add_instr("(void)memcpy(UNBOX_NativeArray({p[1]}), UNBOX_NativeArray({p[0]}), UNTAG_Int({p[2]})*sizeof(val_t));")
644 end
645 else if c == once "NativeString".to_symbol then
646 if n == once "object_id".to_symbol then
647 s = "TAG_Int(UNBOX_NativeString({p[0]}))"
648 else if n == once "atoi".to_symbol then
649 s = "TAG_Int(atoi(UNBOX_NativeString({p[0]})))"
650 else if n == once "[]".to_symbol then
651 s = "TAG_Char(UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})])"
652 else if n == once "[]=".to_symbol then
653 v.add_instr("UNBOX_NativeString({p[0]})[UNTAG_Int({p[1]})]=UNTAG_Char({p[2]});")
654 else if n == once "copy_to".to_symbol then
655 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]}));")
656 end
657 else if n == once "object_id".to_symbol then
658 s = "TAG_Int((bigint){p[0]})"
659 else if n == once "sys".to_symbol then
660 s = "(G_sys)"
661 else if n == once "is_same_type".to_symbol then
662 s = "TAG_Bool((VAL2VFT({p[0]})==VAL2VFT({p[1]})))"
663 else if n == once "exit".to_symbol then
664 v.add_instr("exit(UNTAG_Int({p[1]}));")
665 else if n == once "calloc_array".to_symbol then
666 s = "BOX_NativeArray((val_t*)malloc((UNTAG_Int({p[1]}) * sizeof(val_t))))"
667 else if n == once "calloc_string".to_symbol then
668 s = "BOX_NativeString((char*)malloc((UNTAG_Int({p[1]}) * sizeof(char))))"
669
670 else
671 v.add_instr("fprintf(stderr, \"Intern {n}\\n\"); nit_exit(1);")
672 end
673 if method.signature.return_type != null and s == null then
674 s = "NIT_NULL /*stub*/"
675 end
676 return s
677 end
678 end
679
680 ###############################################################################
681
682 redef class PExpr
683 # Compile the node as an expression
684 # Only the visitor should call it
685 meth compile_expr(v: CompilerVisitor): String is abstract
686
687 # Prepare a call of node as a statement
688 # Only the visitor should call it
689 # It's used for local variable managment
690 meth prepare_compile_stmt(v: CompilerVisitor) do end
691
692 # Compile the node as a statement
693 # Only the visitor should call it
694 meth compile_stmt(v: CompilerVisitor) do printl("Error!")
695 end
696
697 redef class ABlockExpr
698 redef meth compile_stmt(v)
699 do
700 for n in n_expr do
701 v.compile_stmt(n)
702 end
703 end
704 end
705
706 redef class AVardeclExpr
707 redef meth prepare_compile_stmt(v)
708 do
709 var cname = v.get_var
710 v.varnames[variable] = cname
711 end
712
713 redef meth compile_stmt(v)
714 do
715 var cname = v.varnames[variable]
716 if n_expr == null then
717 var t = variable.stype
718 v.add_assignment(cname, "{t.default_cvalue} /*decl variable {variable.name}*/")
719 else
720 var e = v.compile_expr(n_expr)
721 v.add_assignment(cname, e)
722 end
723 end
724 end
725
726 redef class AReturnExpr
727 redef meth compile_stmt(v)
728 do
729 v.has_return = true
730 if n_expr != null then
731 var e = v.compile_expr(n_expr)
732 v.add_assignment(v.return_value, e)
733 end
734 v.add_instr("goto {v.return_label};")
735 end
736 end
737
738 redef class ABreakExpr
739 redef meth compile_stmt(v)
740 do
741 v.add_instr("goto {v.break_label};")
742 end
743 end
744
745 redef class AContinueExpr
746 redef meth compile_stmt(v)
747 do
748 v.add_instr("goto {v.continue_label};")
749 end
750 end
751
752 redef class AAbortExpr
753 redef meth compile_stmt(v)
754 do
755 v.add_instr("fprintf(stderr, \"Aborted\"); {v.printf_locate_error(self)} nit_exit(1);")
756 end
757 end
758
759 redef class ADoExpr
760 redef meth compile_stmt(v)
761 do
762 if n_block != null then
763 v.compile_stmt(n_block)
764 end
765 end
766 end
767
768 redef class AIfExpr
769 redef meth compile_stmt(v)
770 do
771 var e = v.compile_expr(n_expr)
772 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
773 v.free_var(e)
774 if n_then != null then
775 v.indent
776 v.compile_stmt(n_then)
777 v.unindent
778 end
779 if n_else != null then
780 v.add_instr("} else \{ /*if*/")
781 v.indent
782 v.compile_stmt(n_else)
783 v.unindent
784 end
785 v.add_instr("}")
786 end
787 end
788
789 redef class AIfexprExpr
790 redef meth compile_expr(v)
791 do
792 var e = v.compile_expr(n_expr)
793 v.add_instr("if (UNTAG_Bool({e})) \{ /*if*/")
794 v.free_var(e)
795 v.indent
796 var e = v.ensure_var(v.compile_expr(n_then))
797 v.unindent
798 v.add_instr("} else \{ /*if*/")
799 v.free_var(e)
800 v.indent
801 var e2 = v.ensure_var(v.compile_expr(n_else))
802 v.add_assignment(e, e2)
803 v.unindent
804 v.add_instr("}")
805 return e
806 end
807 end
808
809 redef class AControlableBlock
810 meth compile_inside_block(v: CompilerVisitor) is abstract
811 redef meth compile_stmt(v)
812 do
813 var old_break_label = v.break_label
814 var old_continue_label = v.continue_label
815 var id = v.new_number
816 v.break_label = "break_{id}"
817 v.continue_label = "continue_{id}"
818
819 compile_inside_block(v)
820
821
822 v.break_label = old_break_label
823 v.continue_label = old_continue_label
824 end
825 end
826
827 redef class AWhileExpr
828 redef meth compile_inside_block(v)
829 do
830 v.add_instr("while (true) \{ /*while*/")
831 v.indent
832 var e = v.compile_expr(n_expr)
833 v.add_instr("if (!UNTAG_Bool({e})) break; /* while*/")
834 v.free_var(e)
835 if n_block != null then
836 v.compile_stmt(n_block)
837 end
838 v.add_instr("{v.continue_label}: while(0);")
839 v.unindent
840 v.add_instr("}")
841 v.add_instr("{v.break_label}: while(0);")
842 end
843 end
844
845 redef class AForExpr
846 redef meth compile_inside_block(v)
847 do
848 v.compile_stmt(n_vardecl)
849 end
850 end
851
852 redef class AForVardeclExpr
853 redef meth compile_stmt(v)
854 do
855 var e = v.compile_expr(n_expr)
856 var prop = n_expr.stype.local_class.select_method(once "iterator".to_symbol)
857 if prop == null then
858 printl("No iterator")
859 return
860 end
861 var ittype = prop.signature.return_type
862 v.free_var(e)
863 var iter = v.get_var
864 v.add_assignment(iter, prop.compile_call(v, [e]))
865 var prop2 = ittype.local_class.select_method(once "is_ok".to_symbol)
866 if prop2 == null then
867 printl("No is_ok")
868 return
869 end
870 var prop3 = ittype.local_class.select_method(once "item".to_symbol)
871 if prop3 == null then
872 printl("No item")
873 return
874 end
875 var prop4 = ittype.local_class.select_method(once "next".to_symbol)
876 if prop4 == null then
877 printl("No next")
878 return
879 end
880 v.add_instr("while (true) \{ /*for*/")
881 v.indent
882 var ok = v.get_var
883 v.add_assignment(ok, prop2.compile_call(v, [iter]))
884 v.add_instr("if (!UNTAG_Bool({ok})) break; /*for*/")
885 v.free_var(ok)
886 var e = prop3.compile_call(v, [iter])
887 e = v.ensure_var(e)
888 v.varnames[variable] = e
889 var par = parent
890 assert par isa AForExpr
891 var n_block = par.n_block
892 if n_block != null then
893 v.compile_stmt(n_block)
894 end
895 v.add_instr("{v.continue_label}: while(0);")
896 e = prop4.compile_call(v, [iter])
897 assert e == null
898 v.unindent
899 v.add_instr("}")
900 v.add_instr("{v.break_label}: while(0);")
901 end
902 end
903
904 redef class AAssertExpr
905 redef meth compile_stmt(v)
906 do
907 var e = v.compile_expr(n_expr)
908 var s = ""
909 if n_id != null then
910 s = " '{n_id.text}' "
911 end
912 v.add_instr("if (!UNTAG_Bool({e})) \{ fprintf(stderr, \"Assert%s failed\", \"{s}\"); {v.printf_locate_error(self)} nit_exit(1);}")
913 end
914 end
915
916 redef class AVarExpr
917 redef meth compile_expr(v)
918 do
919 return " {v.varnames[variable]} /*{variable.name}*/"
920 end
921 end
922
923 redef class AVarAssignExpr
924 redef meth compile_stmt(v)
925 do
926 var e = v.compile_expr(n_value)
927 v.add_assignment(v.varnames[variable], "{e} /*{variable.name}=*/")
928 end
929 end
930
931 redef class AVarReassignExpr
932 redef meth compile_stmt(v)
933 do
934 var e1 = v.varnames[variable]
935 var e2 = v.compile_expr(n_value)
936 var e3 = assign_method.compile_call(v, [e1, e2])
937 v.add_assignment(v.varnames[variable], "{e3} /*{variable.name}*/")
938 end
939 end
940
941 redef class ASelfExpr
942 redef meth compile_expr(v)
943 do
944 return v.method_params[0]
945 end
946 end
947
948 redef class AOrExpr
949 redef meth compile_expr(v)
950 do
951 var e = v.ensure_var(v.compile_expr(n_expr))
952 v.add_instr("if (!UNTAG_Bool({e})) \{ /* or */")
953 v.free_var(e)
954 v.indent
955 var e2 = v.compile_expr(n_expr2)
956 v.add_assignment(e, e2)
957 v.unindent
958 v.add_instr("}")
959 return e
960 end
961 end
962
963 redef class AAndExpr
964 redef meth compile_expr(v)
965 do
966 var e = v.ensure_var(v.compile_expr(n_expr))
967 v.add_instr("if (UNTAG_Bool({e})) \{ /* and */")
968 v.free_var(e)
969 v.indent
970 var e2 = v.compile_expr(n_expr2)
971 v.add_assignment(e, e2)
972 v.unindent
973 v.add_instr("}")
974 return e
975 end
976 end
977
978 redef class ANotExpr
979 redef meth compile_expr(v)
980 do
981 return " TAG_Bool(!UNTAG_Bool({v.compile_expr(n_expr)}))"
982 end
983 end
984
985 redef class AEeExpr
986 redef meth compile_expr(v)
987 do
988 var e = v.compile_expr(n_expr)
989 var e2 = v.compile_expr(n_expr2)
990 return "TAG_Bool(IS_EQUAL_NN({e},{e2}))"
991 end
992 end
993
994 redef class AIsaExpr
995 redef meth compile_expr(v)
996 do
997 var e = v.compile_expr(n_expr)
998 return n_type.stype.compile_cast(v, e)
999 end
1000 end
1001
1002 redef class AAsCastExpr
1003 redef meth compile_expr(v)
1004 do
1005 var e = v.compile_expr(n_expr)
1006 n_type.stype.compile_type_check(v, e, self)
1007 return e
1008 end
1009 end
1010
1011 redef class ATrueExpr
1012 redef meth compile_expr(v)
1013 do
1014 return " TAG_Bool(true)"
1015 end
1016 end
1017
1018 redef class AFalseExpr
1019 redef meth compile_expr(v)
1020 do
1021 return " TAG_Bool(false)"
1022 end
1023 end
1024
1025 redef class AIntExpr
1026 redef meth compile_expr(v)
1027 do
1028 return " TAG_Int({n_number.text})"
1029 end
1030 end
1031
1032 redef class AFloatExpr
1033 redef meth compile_expr(v)
1034 do
1035 return "BOX_Float({n_float.text})"
1036 end
1037 end
1038
1039 redef class ACharExpr
1040 redef meth compile_expr(v)
1041 do
1042 return " TAG_Char({n_char.text})"
1043 end
1044 end
1045
1046 redef class AStringFormExpr
1047 redef meth compile_expr(v)
1048 do
1049 var prop = stype.local_class.select_method(once "with_native".to_symbol)
1050 compute_string_info
1051 return prop.compile_constructor_call(v, stype , ["BOX_NativeString(\"{_cstring}\")", "TAG_Int({_cstring_length})"])
1052 end
1053
1054 # The raw string value
1055 protected meth string_text: String is abstract
1056
1057 # The string in a C native format
1058 protected attr _cstring: String
1059
1060 # The string length in bytes
1061 protected attr _cstring_length: Int
1062
1063 # Compute _cstring and _cstring_length using string_text
1064 protected meth compute_string_info
1065 do
1066 var len = 0
1067 var str = string_text
1068 var res = new String
1069 var i = 0
1070 while i < str.length do
1071 var c = str[i]
1072 if c == '\\' then
1073 i = i + 1
1074 var c2 = str[i]
1075 if c2 != '{' and c2 != '}' then
1076 res.add(c)
1077 end
1078 c = c2
1079 end
1080 len = len + 1
1081 res.add(c)
1082 i = i + 1
1083 end
1084 _cstring = res
1085 _cstring_length = len
1086 end
1087 end
1088
1089 redef class AStringExpr
1090 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1091 end
1092 redef class AStartStringExpr
1093 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1094 end
1095 redef class AMidStringExpr
1096 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1097 end
1098 redef class AEndStringExpr
1099 redef meth string_text do return n_string.text.substring(1, n_string.text.length - 2)
1100 end
1101
1102 redef class ASuperstringExpr
1103 redef meth compile_expr(v)
1104 do
1105 var prop = stype.local_class.select_method(once "init".to_symbol)
1106 var recv = prop.compile_constructor_call(v, stype, new Array[String])
1107
1108 var prop2 = stype.local_class.select_method(once "append".to_symbol)
1109
1110 var prop3 = stype.local_class.select_method(once "to_s".to_symbol)
1111 for ne in n_exprs do
1112 var e = v.ensure_var(v.compile_expr(ne))
1113 if ne.stype != stype then
1114 v.add_assignment(e, prop3.compile_call(v, [e]))
1115 end
1116 prop2.compile_call(v, [recv, e])
1117 end
1118
1119 return recv
1120 end
1121 end
1122
1123 redef class ANullExpr
1124 redef meth compile_expr(v)
1125 do
1126 return " NIT_NULL /*null*/"
1127 end
1128 end
1129
1130 redef class AArrayExpr
1131 redef meth compile_expr(v)
1132 do
1133 var prop = stype.local_class.select_method(once "with_capacity".to_symbol)
1134 var recv = prop.compile_constructor_call(v, stype, ["TAG_Int({n_exprs.length})"])
1135
1136 var prop2 = stype.local_class.select_method(once "add".to_symbol)
1137 for ne in n_exprs do
1138 var e = v.compile_expr(ne)
1139 prop2.compile_call(v, [recv, e])
1140 end
1141 return recv
1142 end
1143 end
1144
1145 redef class ARangeExpr
1146 redef meth compile_expr(v)
1147 do
1148 var prop = stype.local_class.select_method(propname)
1149 var e = v.compile_expr(n_expr)
1150 var e2 = v.compile_expr(n_expr2)
1151 return prop.compile_constructor_call(v, stype, [e, e2])
1152 end
1153 # The constructor that must be used for the range
1154 protected meth propname: Symbol is abstract
1155 end
1156
1157 redef class ACrangeExpr
1158 redef meth propname do return once "init".to_symbol
1159 end
1160 redef class AOrangeExpr
1161 redef meth propname do return once "without_last".to_symbol
1162 end
1163
1164 redef class ASuperExpr
1165 redef meth compile_stmt(v)
1166 do
1167 var e = compile_expr(v)
1168 if e != null then v.add_instr("{e};")
1169 end
1170
1171 redef meth compile_expr(v)
1172 do
1173 var arity = v.method_params.length - 1
1174 if init_in_superclass != null then
1175 arity = init_in_superclass.signature.arity
1176 end
1177 var args = new Array[String].with_capacity(arity + 1)
1178 args.add(v.method_params[0])
1179 if n_args.length != arity then
1180 for i in [0..arity[ do
1181 args.add(v.method_params[i + 1])
1182 end
1183 else
1184 for na in n_args do
1185 args.add(v.compile_expr(na))
1186 end
1187 end
1188 #return "{prop.cname}({args.join(", ")}) /*super {prop.local_class}::{prop.name}*/"
1189 if init_in_superclass != null then
1190 return init_in_superclass.compile_call(v, args)
1191 else
1192 if prop.global.is_init then args.add("init_table")
1193 return prop.compile_super_call(v, args)
1194 end
1195 end
1196 end
1197
1198 redef class AAttrExpr
1199 redef meth compile_expr(v)
1200 do
1201 var e = v.compile_expr(n_expr)
1202 return prop.compile_access(v, e)
1203 end
1204 end
1205
1206 redef class AAttrAssignExpr
1207 redef meth compile_stmt(v)
1208 do
1209 var e = v.compile_expr(n_expr)
1210 var e2 = v.compile_expr(n_value)
1211 v.add_assignment(prop.compile_access(v, e), e2)
1212 end
1213 end
1214 redef class AAttrReassignExpr
1215 redef meth compile_stmt(v)
1216 do
1217 var e1 = v.compile_expr(n_expr)
1218 var e2 = prop.compile_access(v, e1)
1219 var e3 = v.compile_expr(n_value)
1220 var e4 = assign_method.compile_call(v, [e2, e3])
1221 v.add_assignment(e2, e4)
1222 end
1223 end
1224
1225 redef class ASendExpr
1226 redef meth compile_expr(v)
1227 do
1228 var recv = v.compile_expr(n_expr)
1229 var cargs = new Array[String]
1230 cargs.add(recv)
1231 for a in arguments do
1232 cargs.add(v.compile_expr(a))
1233 end
1234
1235 var e = prop.compile_call(v, cargs)
1236 if prop.global.is_init then
1237 v.invoke_super_init_calls_after(prop)
1238 end
1239 return e
1240 end
1241
1242 redef meth compile_stmt(v)
1243 do
1244 var e = compile_expr(v)
1245 if e != null then
1246 v.add_instr(e + ";")
1247 end
1248 end
1249 end
1250
1251 redef class ASendReassignExpr
1252 redef meth compile_expr(v)
1253 do
1254 var recv = v.compile_expr(n_expr)
1255 var cargs = new Array[String]
1256 cargs.add(recv)
1257 for a in arguments do
1258 cargs.add(v.compile_expr(a))
1259 end
1260
1261 var e2 = read_prop.compile_call(v, cargs)
1262 var e3 = v.compile_expr(n_value)
1263 var e4 = assign_method.compile_call(v, [e2, e3])
1264 cargs.add(e4)
1265 return prop.compile_call(v, cargs)
1266 end
1267 end
1268
1269 redef class ANewExpr
1270 redef meth compile_expr(v)
1271 do
1272 var cargs = new Array[String]
1273 for a in arguments do
1274 cargs.add(v.compile_expr(a))
1275 end
1276 return prop.compile_constructor_call(v, stype, cargs)
1277 end
1278 end
1279
1280 redef class AProxyExpr
1281 redef meth compile_expr(v)
1282 do
1283 return v.compile_expr(n_expr)
1284 end
1285 end
1286
1287 redef class AOnceExpr
1288 redef meth compile_expr(v)
1289 do
1290 var i = v.new_number
1291 var cvar = v.get_var
1292 v.add_decl("static val_t once_value_{cvar}_{i}; static int once_bool_{cvar}_{i};")
1293 v.add_instr("if (once_bool_{cvar}_{i}) {cvar} = once_value_{cvar}_{i};")
1294 v.add_instr("else \{")
1295 v.indent
1296 v.free_var(cvar)
1297 var e = v.compile_expr(n_expr)
1298 v.add_assignment(cvar, e)
1299 v.add_instr("once_value_{cvar}_{i} = {cvar};")
1300 v.add_instr("once_bool_{cvar}_{i} = true;")
1301 v.unindent
1302 v.add_instr("}")
1303 return cvar
1304 end
1305 end