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