1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Global compilation of a Nit program
19 # Techniques used are:
20 # * heterogeneous generics
24 module global_compiler
28 import auto_super_init
29 import rapid_type_analysis
31 redef class ToolContext
33 var opt_output
: OptionString = new OptionString("Output file", "-o", "--output")
36 var opt_no_cc
: OptionBool = new OptionBool("Do not invoke C compiler", "--no-cc")
41 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
)
45 redef class ModelBuilder
46 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
49 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
51 var compiler
= new GlobalCompiler(mainmodule
, runtime_type_analysis
, self)
52 var v
= new GlobalCompilerVisitor(compiler
)
54 v
.add_decl
("#include <stdlib.h>")
55 v
.add_decl
("#include <stdio.h>")
56 v
.add_decl
("#include <string.h>")
58 # TODO: Better way to activate the GC
59 #v.add_decl("#include <gc/gc.h>")
60 v
.add_decl
("#define GC_MALLOC(x) calloc(1, (x))")
62 # Declare structure for each live type
64 v
.add_decl
("typedef struct \{int classid;\} val;")
65 for t
in runtime_type_analysis
.live_types
do
66 compiler
.declare_runtimeclass
(v
, t
)
69 v
.add_decl
("extern int glob_argc;")
70 v
.add_decl
("extern char **glob_argv;")
71 v
.add_decl
("extern val *glob_sys;")
73 # Class names (for the class_name and output_class_name methods)
75 v
.add_decl
("extern const char const * class_names[];")
76 v
.add
("const char const * class_names[] = \{")
77 for t
in runtime_type_analysis
.live_types
do
78 v
.add
("\"{t}\
", /* {compiler.classid(t)} */")
83 # Init instance code (allocate and init-arguments)
85 for t
in runtime_type_analysis
.live_types
do
86 if t
.ctype
!= "val*" then continue
87 compiler
.generate_init_instance
(t
)
90 # The main function of the C
92 v
= new GlobalCompilerVisitor(compiler
)
93 v
.add_decl
("int glob_argc;")
94 v
.add_decl
("char **glob_argv;")
95 v
.add_decl
("val *glob_sys;")
96 v
.add_decl
("int main(int argc, char** argv) \{")
97 v
.add
("glob_argc = argc; glob_argv = argv;")
98 var main_type
= mainmodule
.sys_type
99 if main_type
== null then return # Nothing to compile
100 var glob_sys
= v
.init_instance
(main_type
)
101 v
.add
("glob_sys = {glob_sys};")
102 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
103 if main_init
!= null then
104 v
.send
(main_init
, [glob_sys
])
106 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
107 if main_method
!= null then
108 v
.send
(main_method
, [glob_sys
])
112 # Compile until all runtime_functions are visited
114 while not compiler
.todos
.is_empty
do
115 var m
= compiler
.todos
.shift
116 self.toolcontext
.info
("Compile {m.mmethoddef} for {m.recv} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
117 m
.mmethoddef
.compile_to_c
(compiler
, self, m
.recv
)
119 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
121 # Generate the .h and .c files
123 var outname
= self.toolcontext
.opt_output
.value
124 if outname
== null then
125 outname
= "{mainmodule.name}.bin"
128 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
129 var h
= new OFStream.open
(hfilename
)
130 for l
in compiler
.header
.decl_lines
do
136 var cfiles
= new Array[String]
138 var file
: nullable OFStream = null
143 for vis
in compiler
.visitors
do
144 count
+= vis
.lines
.length
145 if file
== null or count
> 10000 then
147 if file
!= null then file
.close
148 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
149 cfiles
.add
(cfilename
)
150 file
= new OFStream.open
(cfilename
)
151 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
152 count
= vis
.lines
.length
154 if vis
!= compiler
.header
then
155 for l
in vis
.decl_lines
do
160 for l
in vis
.lines
do
165 if file
!= null then file
.close
167 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
169 # Generate the Makefile
171 var makename
= ".nit_compile/{mainmodule.name}.mk"
172 var makefile
= new OFStream.open
(makename
)
174 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
175 makefile
.write
("all: {outname}\n\n")
177 var ofiles
= new Array[String]
179 var o
= f
.strip_extension
(".c") + ".o"
180 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -I .nit_compile -I ../clib -c -o {o} {f}\n\n")
184 makefile
.write
("{outname}: {ofiles.join(" ")} {compiler.extern_bodies.join(" ")}\n\t$(CC) -Wl,--warn-unresolved-symbols $(CFLAGS) $(LDFLAGS) $(LDLIBS) -I .nit_compile -I ../clib -o {outname} {ofiles.join(" ")} {compiler.extern_bodies.join(" ")}\n\n")
186 self.toolcontext
.info
("Generated makefile: {makename}", 2)
189 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
191 # Execute the Makefile
193 if self.toolcontext
.opt_no_cc
.value
then return
196 self.toolcontext
.info
("*** COMPILING C ***", 1)
197 self.toolcontext
.info
("make -f {makename} -j 4", 2)
200 if self.toolcontext
.verbose_level
>= 3 then
201 res
= sys
.system
("make -f {makename} -j 4 2>&1")
203 res
= sys
.system
("make -f {makename} -j 4 2>&1 >/dev/null")
206 toolcontext
.error
(null, "make failed! Error code: {res}.")
210 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
214 # Singleton that store the knowledge about the compilation process
215 private class GlobalCompiler
216 # The main module of the program
217 var mainmodule
: MModule
219 # The result of the RTA (used to know live types and methods)
220 var runtime_type_analysis
: RapidTypeAnalysis
222 # The modeulbuilder used to know the model and the AST
223 var modelbuilder
: ModelBuilder
225 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, modelbuilder
: ModelBuilder)
227 self.mainmodule
= mainmodule
228 self.runtime_type_analysis
= runtime_type_analysis
229 self.modelbuilder
= modelbuilder
230 self.live_primitive_types
= new Array[MClassType]
231 for t
in runtime_type_analysis
.live_types
do
232 if t
.ctype
!= "val*" then
233 self.live_primitive_types
.add
(t
)
238 # Subset of runtime_type_analysis.live_types that contains only primitive types
239 var live_primitive_types
: Array[MClassType]
241 # runtime_functions that need to be compiled
242 private var todos
: List[RuntimeFunction] = new List[RuntimeFunction]
244 # runtime_functions already seen (todo or done)
245 private var seen
: HashSet[RuntimeFunction] = new HashSet[RuntimeFunction]
246 fun todo
(m
: RuntimeFunction)
248 if seen
.has
(m
) then return
253 # Where global declaration are stored (the main .h)
255 # FIXME: should not be a vistor but just somewhere to store lines
256 # FIXME: should not have a global .h since its does no helps recompilation
257 var header
: nullable GlobalCompilerVisitor = null
259 # The list of all associated visitors
260 # Used to generate .c files
261 private var visitors
: List[GlobalCompilerVisitor] = new List[GlobalCompilerVisitor]
263 # List of additional .c files required to compile (native interface)
264 var extern_bodies
= new ArraySet[String]
266 # Return the C symbol associated to a live type runtime
267 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
268 fun classid
(mtype
: MClassType): String
270 if self.classids
.has_key
(mtype
) then
271 return self.classids
[mtype
]
273 print
"No classid for {mtype}"
277 # Cache for classid (computed by declare_runtimeclass)
278 private var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
280 # Declare C structures and identifiers for a runtime class
281 fun declare_runtimeclass
(v
: GlobalCompilerVisitor, mtype
: MClassType)
283 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
284 v
.add_decl
("/* runtime class {mtype} */")
285 var idnum
= classids
.length
286 var idname
= "ID_" + mtype
.c_name
287 self.classids
[mtype
] = idname
288 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
289 v
.add_decl
("struct {mtype.c_name} \{")
290 v
.add_decl
("int classid; /* must be {idname} */")
291 if mtype
.ctype
!= "val*" then
292 v
.add_decl
("{mtype.ctype} value;")
294 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
295 for p
in cd
.intro_mproperties
do
296 if not p
isa MAttribute then continue
297 var t
= p
.intro
.static_mtype
.as(not null)
298 t
= t
.anchor_to
(self.mainmodule
, mtype
)
299 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
305 # Generate the init-instance of a live type (allocate + init-instance)
306 fun generate_init_instance
(mtype
: MClassType)
308 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
309 assert mtype
.ctype
== "val*"
310 var v
= new GlobalCompilerVisitor(self)
312 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}(void);")
313 v
.add_decl
("/* allocate {mtype} */")
314 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}(void) \{")
315 var res
= v
.new_var
(mtype
)
316 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
317 v
.add
("{res}->classid = {self.classid(mtype)};")
319 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
321 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
322 for npropdef
in n
.n_propdefs
do
323 if npropdef
isa AAttrPropdef then
324 npropdef
.init_expr
(v
, res
)
328 v
.add
("return {res};")
332 # look for a needed .h and .c file for a given .nit source-file
333 # FIXME: bad API, parameter should be a MModule, not its source-file
334 fun add_extern
(file
: String)
336 file
= file
.strip_extension
(".nit")
337 var tryfile
= file
+ ".nit.h"
338 if tryfile
.file_exists
then
339 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
341 tryfile
= file
+ "_nit.h"
342 if tryfile
.file_exists
then
343 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
345 tryfile
= file
+ ".nit.c"
346 if tryfile
.file_exists
then
347 self.extern_bodies
.add
(tryfile
)
349 tryfile
= file
+ "_nit.c"
350 if tryfile
.file_exists
then
351 self.extern_bodies
.add
(tryfile
)
353 #(new OFStream.open("{file.basename("")}._nitni.h")).close
358 # Mangle a string to be a unique valid C identifier
359 fun to_cmangle
: String
362 var underscore
= false
364 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
370 res
.append
('_'.ascii
.to_s
)
373 if c
>= '0' and c
<= '9' then
376 else if c
== '_' then
381 res
.append
(c
.ascii
.to_s
)
389 # Escape " \ ' and non printable characters for literal C strings or characters
390 fun escape_to_c
: String
396 else if c
== '\0' then
398 else if c
== '"' then
400 else if c == '\'' then
402 else if c == '\\
' then
404 else if c.ascii < 32 then
405 b.append("\\{c.ascii.to_base(8, false)}")
415 # Return the C type associated to a given Nit static type
421 # Return the name of the C structure associated to a Nit live type
422 # FIXME: move to GlobalCompiler so we can check that self is a live type
423 fun c_name: String is abstract
424 private var c_name_cache: nullable String
427 redef class MClassType
430 var res = self.c_name_cache
431 if res != null then return res
432 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
433 self.c_name_cache = res
437 redef fun ctype: String
439 if mclass.name == "Int" then
441 else if mclass.name == "Bool" then
443 else if mclass.name == "Char" then
445 else if mclass.name == "Float" then
447 else if mclass.name == "NativeString" then
449 else if mclass.name == "NativeArray" then
450 assert self isa MGenericType
451 return "{self.arguments.first.ctype}*"
452 else if mclass.kind == extern_kind then
460 redef class MGenericType
463 var res = self.c_name_cache
464 if res != null then return res
466 for t in self.arguments do
469 self.c_name_cache = res
474 redef class MNullableType
477 var res = self.c_name_cache
478 if res != null then return res
479 res = "nullable_{self.mtype.c_name}"
480 self.c_name_cache = res
485 # A C function associated to a Nit method
486 # Because of customization, a given Nit method can be compiler more that once
487 private class RuntimeFunction
488 # The associated Nit method
489 var mmethoddef: MMethodDef
491 # The considered reciever
492 # (usually is a live type but no strong guarantee)
495 # The mangled c name of the runtime_function
498 var res = self.c_name_cache
499 if res != null then return res
500 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
501 res = self.mmethoddef.c_name
503 res = "{mmethoddef.c_name}__{recv.c_name}"
505 self.c_name_cache = res
509 private var c_name_cache: nullable String = null
512 # used in the compiler worklist
514 if not o isa RuntimeFunction then return false
515 if self.mmethoddef != o.mmethoddef then return false
516 if self.recv != o.recv then return false
521 # used in the compiler work-list
523 var res = self.mmethoddef.hash + self.recv.hash
529 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
530 return self.mmethoddef.to_s
532 return "{self.mmethoddef}@{self.recv}"
536 # Implements a call of the runtime_function
537 # May inline the body
538 fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
540 var ret = self.mmethoddef.msignature.return_mtype
541 if self.mmethoddef.mproperty.is_new then
542 ret = arguments.first.mtype
545 ret = v.resolve_for(ret, arguments.first)
547 if self.mmethoddef.can_inline(v) then
548 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
549 frame.returnlabel = v.get_name("RET_LABEL")
551 frame.returnvar = v.new_var(ret)
553 var old_frame = v.frame
555 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
556 self.mmethoddef.compile_inside_to_c(v, arguments)
557 v.add("{frame.returnlabel.as(not null)}:(void)0;")
560 return frame.returnvar
562 v.adapt_signature(self.mmethoddef, arguments)
563 v.compiler.todo(self)
565 v.add("{self.c_name}({arguments.join(",")});")
568 var res = v.new_var(ret)
569 v.add("{res} = {self.c_name}({arguments.join(",")});")
575 # A runtime variable hold a runtime value in C
576 # Runtime variables are associated to local variables and intermediate results
577 private class RuntimeVariable
578 # The name of the variable in the C code
581 # The static type of the variable (as declard in C)
584 # The current casted type of the variable (as known in Nit)
587 redef fun to_s do return name
589 redef fun inspect do return "<{inspect_head} {name}:{mtype}({mcasttype})>"
592 # Visit the AST to generate the C code.
593 # Because of inlining, a visitor can visit more than one property.
594 private class GlobalCompilerVisitor
595 # The associated compiler
596 var compiler: GlobalCompiler
598 init(compiler: GlobalCompiler)
600 self.compiler = compiler
601 compiler.visitors.add(self)
604 # Alias for self.compiler.mainmodule.object_type
605 fun object_type: MClassType do return self.compiler.mainmodule.object_type
607 # Alias for self.compiler.mainmodule.bool_type
608 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
610 # Force to get the primitive class named `name' or abort
611 fun get_class
(name
: String): MClass
613 return self.compiler
.mainmodule
.get_primitive_class
(name
)
616 # Force to get the primitive property named `name' in the instance `recv' or abort
617 fun get_property
(name
: String, recv
: MType): MMethod
619 return self.compiler
.mainmodule
.force_get_primitive_method
(name
, recv
)
623 var frame
: nullable Frame
625 # Anchor a type to the main module and the current receiver
626 fun anchor
(mtype
: MType): MType
628 if not mtype
.need_anchor
then return mtype
629 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
630 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
633 # Add a line in the main part of the generated C
640 # (used for local or global declaration)
641 fun add_decl
(s
: String)
643 self.decl_lines
.add
(s
)
646 private var lines
: List[String] = new List[String]
647 private var decl_lines
: List[String] = new List[String]
649 # The current visited AST node
650 var current_node
: nullable AExpr = null
652 # Compile an expression an return its
653 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
655 var old
= self.current_node
656 self.current_node
= nexpr
657 var res
= nexpr
.expr
(self).as(not null)
658 if mtype
!= null then
659 mtype
= self.anchor
(mtype
)
660 res
= self.autobox
(res
, mtype
)
662 self.current_node
= old
666 # Unsafely cast a value to a new type
667 # ENSURE: return.name == value.name
668 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
670 mtype
= self.anchor
(mtype
)
671 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
675 var valmtype
= value
.mtype
676 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
677 var res
= new RuntimeVariable(value
.name
, value
.mtype
, valmtype
.mtype
)
680 var res
= new RuntimeVariable(value
.name
, value
.mtype
, mtype
)
685 # Box or unbox a value to another type iff a C type conversion is needed
686 # ENSURE: result.mtype.ctype == mtype.ctype
687 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
689 if value
.mtype
.ctype
== mtype
.ctype
then
691 else if value
.mtype
.ctype
== "val*" then
692 return self.new_expr
("((struct {mtype.c_name}*){value})->value /* autounbox from {value.mtype} to {mtype} */", mtype
)
693 else if mtype
.ctype
== "val*" then
694 var valtype
= value
.mtype
.as(MClassType)
695 var res
= self.new_var
(mtype
)
696 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
697 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
698 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
701 self.add
("{res} = GC_MALLOC(sizeof(struct {valtype.c_name})); /* autobox from {value.mtype} to {mtype} */")
702 self.add
("{res}->classid = {self.compiler.classid(valtype)};")
703 self.add
("((struct {valtype.c_name}*){res})->value = {value};")
706 # Bad things will append!
707 var res
= self.new_var
(mtype
)
708 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
709 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
714 # Correctly assign a left and a right value
715 # Boxing and unboxing is performed if required
716 fun assign
(left
, right
: RuntimeVariable)
718 right
= self.autobox
(right
, left
.mtype
)
719 self.add
("{left} = {right};")
723 # Alias for `self.expr(nexpr, self.bool_type)'
724 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
726 return expr
(nexpr
, bool_type
)
730 fun stmt
(nexpr
: nullable AExpr)
732 if nexpr
== null then return
733 var old
= self.current_node
734 self.current_node
= nexpr
736 self.current_node
= old
739 # Safely show a debug message on the current node and repeat the message in the C code
740 fun debug
(message
: String)
742 var node
= self.current_node
748 self.add
("/* DEBUG: {message} */")
751 # Return a new uninitialized local runtime_variable
752 fun new_var
(mtype
: MType): RuntimeVariable
754 if mtype
isa MNullType then
755 mtype
= self.object_type
757 mtype
= self.anchor
(mtype
)
759 var name
= self.get_name
("var")
760 var res
= new RuntimeVariable(name
, mtype
, mtype
)
761 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
765 # Return a new local runtime_variable initialized with the C expression `cexpr'.
766 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
768 var res
= new_var
(mtype
)
769 self.add
("{res} = {cexpr};")
773 # Return the local runtime_variable associated to a Nit local variable
774 fun variable
(variable
: Variable): RuntimeVariable
776 if self.variables
.has_key
(variable
) then
777 return self.variables
[variable
]
779 var name
= self.get_name
("var_{variable.name}")
780 var mtype
= variable
.declared_type
.as(not null)
781 mtype
= self.anchor
(mtype
)
782 var res
= new RuntimeVariable(name
, mtype
, mtype
)
783 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
784 self.variables
[variable
] = res
789 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
791 # Return a new name based on `s' and unique in the visitor
792 fun get_name
(s
: String): String
794 if not self.names
.has
(s
) then
798 var i
= self.last
+ 1
801 if not self.names
.has
(s2
) then
810 private var last
: Int = 0
812 private var names
: HashSet[String] = new HashSet[String]
814 # Generate a return with the value `s'
815 fun ret
(s
: RuntimeVariable)
817 self.assign
(self.frame
.returnvar
.as(not null), s
)
818 self.add
("goto {self.frame.returnlabel.as(not null)};")
821 # The runtime types that are acceptable for a given receiver.
822 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
824 var mtype
= recv
.mcasttype
825 var cache
= self.collect_types_cache
826 if cache
.has_key
(mtype
) then
829 var types
= new Array[MClassType]
830 var mainmodule
= self.compiler
.mainmodule
831 for t
in self.compiler
.runtime_type_analysis
.live_types
do
832 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
839 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
841 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
843 if not mtype
.need_anchor
then return mtype
844 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
845 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
849 # Generate a polymorphic send for the method `m' and the arguments `args'
850 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable
852 var types
= self.collect_types
(args
.first
)
854 var res
: nullable RuntimeVariable
855 var ret
= m
.intro
.msignature
.return_mtype
857 ret
= args
.first
.mtype
858 res
= self.new_var
(ret
)
859 else if ret
== null then
862 ret
= self.resolve_for
(ret
, args
.first
)
863 res
= self.new_var
(ret
)
866 if types
.is_empty
then
867 self.add
("/*BUG: no live types for {args.first.mtype} . {m}*/")
870 self.add
("/* send {m} on {args.first}: {args.first.mcasttype} (declared {args.first.mtype}) */")
871 if args
.first
.mtype
.ctype
!= "val*" then
872 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, args
.first
.mtype
)
873 if propdefs
.length
== 0 then
874 self.add
("/* skip {args.first.mcasttype}, no method {m} */")
877 assert propdefs
.length
== 1
878 var propdef
= propdefs
.first
879 var res2
= self.call
(propdef
, args
.first
.mtype
.as(MClassType), args
)
880 if res
!= null then self.assign
(res
, res2
.as(not null))
883 if args
.first
.mcasttype
isa MNullableType then
884 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
885 if m
.name
== "==" then
887 if args
[1].mcasttype
.ctype
== "val*" then
888 self.add
("{res} = ({args[1]} == NULL);")
890 self.add
("{res} = 0; /* {args[1]}: {args[1].mcasttype} cannot be null */")
892 else if m
.name
== "!=" then
894 if args
[1].mcasttype
.ctype
== "val*" then
895 self.add
("{res} = ({args[1]} != NULL);")
897 self.add
("{res} = 1; /* {args[1]}: {args[1].mcasttype} cannot be null */")
900 self.add_abort
("Reciever is null")
904 self.add
("switch({args.first}->classid) \{")
905 var defaultpropdef
: nullable MMethodDef = null
907 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
908 if propdefs
.length
== 0 then
909 self.add
("/* skip {t}, no method {m} */")
912 var propdef
= propdefs
.first
913 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
914 defaultpropdef
= propdef
917 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
918 var res2
= self.call
(propdef
, t
, args
)
919 if res
!= null then self.assign
(res
, res2
.as(not null))
922 if defaultpropdef
!= null then
923 self.add
("default: /* default is Object */")
924 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
925 if res
!= null then self.assign
(res
, res2
.as(not null))
927 self.add
("default: /* bug */")
928 self.bugtype
(args
.first
)
934 fun check_valid_reciever
(recvtype
: MClassType)
936 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
937 print
"{recvtype} is not a live type"
941 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
943 check_valid_reciever
(recvtype
)
944 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
945 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
946 recvtype
= m
.mclassdef
.bound_mtype
948 var recv
= self.autobox
(args
.first
, recvtype
)
949 recv
= self.autoadapt
(recv
, recvtype
)
951 var vararg_rank
= m
.msignature
.vararg_rank
952 if vararg_rank
>= 0 then
953 assert args
.length
>= m
.msignature
.arity
+ 1 # because of self
955 args
= new Array[RuntimeVariable]
957 args
.add
(rawargs
.first
) # recv
959 for i
in [0..vararg_rank
[ do
960 args
.add
(rawargs
[i
+1])
963 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-m
.msignature
.arity
964 var vararg
= new Array[RuntimeVariable]
965 for i
in [vararg_rank
..vararg_lastrank
] do
966 vararg
.add
(rawargs
[i
+1])
968 # FIXME: its it to late to determine the vararg type, this should have been done during a previous analysis
969 var elttype
= m
.msignature
.parameter_mtypes
[vararg_rank
]
970 elttype
= self.resolve_for
(elttype
, recv
)
971 args
.add
(self.array_instance
(vararg
, elttype
))
973 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
974 args
.add
(rawargs
[i
+1])
979 assert args
.length
== m
.msignature
.arity
+ 1 # because of self
982 var rm
= new RuntimeFunction(m
, recvtype
)
983 return rm
.call
(self, args
)
986 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
988 var recv
= args
.first
989 for i
in [0..m
.msignature
.arity
[ do
990 var t
= m
.msignature
.parameter_mtypes
[i
]
991 if i
== m
.msignature
.vararg_rank
then
994 t
= self.resolve_for
(t
, recv
)
995 args
[i
+1] = self.autobox
(args
[i
+1], t
)
999 fun bugtype
(recv
: RuntimeVariable)
1001 if recv
.mtype
.ctype
!= "val*" then return
1002 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
1005 # Generate a polymorphic attribute read
1006 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1008 var types
= self.collect_types
(recv
)
1010 var ret
= a
.intro
.static_mtype
.as(not null)
1011 ret
= self.resolve_for
(ret
, recv
)
1012 var res
= self.new_var
(ret
)
1014 if types
.is_empty
then
1015 self.add
("/*BUG: no live types for {recv.mtype} . {a}*/")
1018 self.add
("/* read {a} on {recv.mcasttype} */")
1019 self.add
("switch({recv}->classid) \{")
1021 self.add
("case {self.compiler.classid(t)}:")
1022 var recv2
= self.autoadapt
(recv
, t
)
1023 var ta
= a
.intro
.static_mtype
.as(not null)
1024 ta
= self.resolve_for
(ta
, recv2
)
1025 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1026 if not ta
isa MNullableType then
1027 if ta
.ctype
== "val*" then
1028 self.add
("if ({res2} == NULL) \{")
1029 self.add_abort
("Uninitialized attribute {a.name}")
1032 self.add
("/*NOTYET isset on primitive attributes*/")
1035 self.assign
(res
, res2
)
1038 self.add
("default: /* Bug */")
1045 # Generate a polymorphic attribute write
1046 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1048 var types
= self.collect_types
(recv
)
1050 if types
.is_empty
then
1051 self.add
("/*BUG: no live types for {recv.mtype} . {a}*/")
1054 self.add
("/* write {a} on {recv.mcasttype} */")
1055 self.add
("switch({recv}->classid) \{")
1057 self.add
("case {self.compiler.classid(t)}:")
1058 var recv2
= self.autoadapt
(recv
, t
)
1059 var ta
= a
.intro
.static_mtype
.as(not null)
1060 ta
= self.resolve_for
(ta
, recv2
)
1061 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1064 self.add
("default: /* Bug*/")
1069 # Generate a alloc-instance + init-attributes
1070 fun init_instance
(mtype
: MClassType): RuntimeVariable
1072 mtype
= self.anchor
(mtype
).as(MClassType)
1073 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1074 debug
"problem: {mtype} was detected dead"
1076 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1080 # Generate a polymorphic subtype test
1081 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1083 mtype
= self.anchor
(mtype
)
1084 var types
= self.collect_types
(value
)
1086 var res
= self.new_var
(bool_type
)
1088 self.add
("/* isa {mtype} on {value.mcasttype} */")
1089 if value
.mcasttype
isa MNullableType then
1090 self.add
("if ({value} == NULL) \{")
1091 if mtype
isa MNullableType then
1092 self.add
("{res} = 1; /* isa {mtype} */")
1094 self.add
("{res} = 0; /* not isa {mtype} */")
1096 self.add
("\} else ")
1098 self.add
("switch({value}->classid) \{")
1100 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1101 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1104 self.add
("{res} = 1;")
1106 self.add
("default:")
1107 self.add
("{res} = 0;")
1113 # Generate a Nit "is" for two runtime_variables
1114 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1116 var res
= self.new_var
(bool_type
)
1117 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1122 if value1
.mtype
.ctype
!= "val*" then
1123 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
1124 self.add
("{res} = {value1} == {value2};")
1125 else if value2
.mtype
.ctype
!= "val*" then
1126 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1128 var mtype1
= value1
.mtype
.as(MClassType)
1129 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1130 self.add
("if ({res}) \{")
1131 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1135 var s
= new Array[String]
1136 for t
in self.compiler
.live_primitive_types
do
1137 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1138 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1139 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1142 self.add
("{res} = {value1} == {value2};")
1144 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1150 # Generate a check-init-instance
1151 # TODO: is an empty stub currently
1152 fun check_init_instance
(recv
: RuntimeVariable)
1156 # Generate an integer value
1157 fun int_instance
(value
: Int): RuntimeVariable
1159 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1160 self.add
("{res} = {value};")
1164 # Generate an array value
1165 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1167 elttype
= self.anchor
(elttype
)
1168 var res
= self.init_instance
(self.get_class
("Array").get_mtype
([elttype
]))
1169 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1170 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1171 self.add
("{nat} = GC_MALLOC({array.length} * sizeof({elttype.ctype}));")
1172 for i
in [0..array
.length
[ do
1173 var r
= self.autobox
(array
[i
], elttype
)
1174 self.add
("{nat}[{i}] = {r};")
1176 var length
= self.int_instance
(array
.length
)
1177 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1178 self.check_init_instance
(res
)
1183 # Generate a string value
1184 fun string_instance
(string
: String): RuntimeVariable
1186 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1187 self.add
("{nat} = \"{string.escape_to_c}\
";")
1188 var res
= self.init_instance
(self.get_class
("String").mclass_type
)
1189 var length
= self.int_instance
(string
.length
)
1190 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1191 self.check_init_instance
(res
)
1195 # Generate generic abort
1196 # used by aborts, asserts, casts, etc.
1197 fun add_abort
(message
: String)
1199 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1200 self.add
("fprintf(stderr, \"%s
(%s
:%d
)\\n\
", \"{message.escape_to_c}\
", \"{self.current_node.location.file.filename.escape_to_c}\
", {current_node.location.line_start});")
1202 self.add
("fprintf(stderr, \"%s\\n\
", \"{message.escape_to_c}\
");")
1204 self.add
("exit(1);")
1208 # A frame correspond to a visited property in a GlobalCompilerVisitor
1210 # The associated visitor
1212 var visitor
: GlobalCompilerVisitor
1214 # The executed property.
1215 # A Method in case of a call, an attribute in case of a default initialization.
1216 var mpropdef
: MPropDef
1218 # The static type of the receiver
1219 var receiver
: MClassType
1221 # Arguments of the method (the first is the receiver)
1222 var arguments
: Array[RuntimeVariable]
1224 # The runtime_variable associated to the return (in a function)
1225 var returnvar
: nullable RuntimeVariable = null
1227 # The label at the end of the property
1228 var returnlabel
: nullable String = null
1231 redef class MPropDef
1232 private var c_name_cache
: nullable String
1234 # The mangled name associated to the property
1237 var res
= self.c_name_cache
1238 if res
!= null then return res
1239 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1240 self.c_name_cache
= res
1245 redef class MMethodDef
1246 # Can the body be inlined?
1247 private fun can_inline
(v
: GlobalCompilerVisitor): Bool
1249 var modelbuilder
= v
.compiler
.modelbuilder
1250 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1251 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1252 return npropdef
.can_inline
1253 else if self.mproperty
.name
== "init" then
1260 # Inline the body in another visitor
1261 private fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1263 var modelbuilder
= v
.compiler
.modelbuilder
1264 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1265 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1266 npropdef
.compile_to_c
(v
, self, arguments
)
1267 else if self.mproperty
.name
== "init" then
1268 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1269 nclassdef
.compile_to_c
(v
, self, arguments
)
1276 # Compile the body in a new visitor
1277 private fun compile_to_c
(compiler
: GlobalCompiler, modelbuilder
: ModelBuilder, recv
: MClassType)
1279 if not recv
.is_subtype
(compiler
.mainmodule
, null, self.mclassdef
.bound_mtype
) then
1280 print
("problem: why do we compile {self} for {recv}?")
1284 var v
= new GlobalCompilerVisitor(compiler
)
1285 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1286 var arguments
= new Array[RuntimeVariable]
1287 var frame
= new Frame(v
, self, recv
, arguments
)
1290 var sig
= new Buffer
1291 var comment
= new Buffer
1292 var ret
= self.msignature
.return_mtype
1294 ret
= v
.resolve_for
(ret
, selfvar
)
1295 sig
.append
("{ret.ctype} ")
1296 else if self.mproperty
.is_new
then
1298 sig
.append
("{ret.ctype} ")
1302 sig
.append
(self.c_name
)
1303 if recv
!= self.mclassdef
.bound_mtype
then
1304 sig
.append
("__{recv.c_name}")
1306 sig
.append
("({recv.ctype} self")
1307 comment
.append
("(self: {recv}")
1308 arguments
.add
(selfvar
)
1309 for i
in [0..self.msignature
.arity
[ do
1310 var mtype
= self.msignature
.parameter_mtypes
[i
]
1311 if i
== self.msignature
.vararg_rank
then
1312 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1314 mtype
= v
.resolve_for
(mtype
, selfvar
)
1315 comment
.append
(", {mtype}")
1316 sig
.append
(", {mtype.ctype} p{i}")
1317 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1318 arguments
.add
(argvar
)
1323 comment
.append
(": {ret}")
1325 compiler
.header
.add_decl
("{sig};")
1327 v
.add_decl
("/* method {self} for {comment} */")
1328 v
.add_decl
("{sig} \{")
1329 #v.add("printf(\"method {self} for {comment}\\n\");")
1331 frame
.returnvar
= v
.new_var
(ret
)
1333 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1335 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1336 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1337 npropdef
.compile_to_c
(v
, self, arguments
)
1338 else if self.mproperty
.name
== "init" then
1339 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1340 nclassdef
.compile_to_c
(v
, self, arguments
)
1345 v
.add
("{frame.returnlabel.as(not null)}:;")
1347 v
.add
("return {frame.returnvar.as(not null)};")
1353 redef class APropdef
1354 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1356 v
.add
("printf(\"Not implemented
{class_name} {mpropdef} at
{location.to_s}\\n\
");")
1357 debug
("Not yet implemented")
1360 private fun can_inline
: Bool do return true
1363 redef class AConcreteMethPropdef
1364 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1366 for i
in [0..mpropdef
.msignature
.arity
[ do
1367 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1368 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1370 # Call the implicit super-init
1371 var auto_super_inits
= self.auto_super_inits
1372 if auto_super_inits
!= null then
1373 var selfarg
= [arguments
.first
]
1374 for auto_super_init
in auto_super_inits
do
1375 if auto_super_init
.intro
.msignature
.arity
== 0 then
1376 v
.send
(auto_super_init
, selfarg
)
1378 v
.send
(auto_super_init
, arguments
)
1383 v
.stmt
(self.n_block
)
1386 redef fun can_inline
1388 if self.auto_super_inits
!= null then return false
1389 var nblock
= self.n_block
1390 if nblock
== null then return true
1391 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
1392 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
1397 redef class AInternMethPropdef
1398 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1400 var pname
= mpropdef
.mproperty
.name
1401 var cname
= mpropdef
.mclassdef
.mclass
.name
1402 var ret
= mpropdef
.msignature
.return_mtype
1404 ret
= v
.resolve_for
(ret
, arguments
.first
)
1406 if pname
!= "==" and pname
!= "!=" then
1407 v
.adapt_signature
(mpropdef
, arguments
)
1409 if cname
== "Int" then
1410 if pname
== "output" then
1411 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1413 else if pname
== "object_id" then
1414 v
.ret
(arguments
.first
)
1416 else if pname
== "+" then
1417 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1419 else if pname
== "-" then
1420 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1422 else if pname
== "unary -" then
1423 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1425 else if pname
== "succ" then
1426 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1428 else if pname
== "prec" then
1429 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1431 else if pname
== "*" then
1432 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1434 else if pname
== "/" then
1435 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1437 else if pname
== "%" then
1438 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1440 else if pname
== "lshift" then
1441 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1443 else if pname
== "rshift" then
1444 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1446 else if pname
== "==" then
1447 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1449 else if pname
== "!=" then
1450 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1451 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1453 else if pname
== "<" then
1454 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1456 else if pname
== ">" then
1457 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1459 else if pname
== "<=" then
1460 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1462 else if pname
== ">=" then
1463 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1465 else if pname
== "to_f" then
1466 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1468 else if pname
== "ascii" then
1469 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1472 else if cname
== "Char" then
1473 if pname
== "output" then
1474 v
.add
("printf(\"%c\
", {arguments.first});")
1476 else if pname
== "object_id" then
1477 v
.ret
(arguments
.first
)
1479 else if pname
== "==" then
1480 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1482 else if pname
== "!=" then
1483 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1484 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1486 else if pname
== "succ" then
1487 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1489 else if pname
== "prec" then
1490 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1492 else if pname
== "<" then
1493 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1495 else if pname
== ">" then
1496 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1498 else if pname
== "<=" then
1499 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1501 else if pname
== ">=" then
1502 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1504 else if pname
== "to_i" then
1505 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
1507 else if pname
== "ascii" then
1508 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
1511 else if cname
== "Bool" then
1512 if pname
== "output" then
1513 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
1515 else if pname
== "object_id" then
1516 v
.ret
(arguments
.first
)
1518 else if pname
== "==" then
1519 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1521 else if pname
== "!=" then
1522 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1523 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1526 else if cname
== "Float" then
1527 if pname
== "output" then
1528 v
.add
("printf(\"%f\\n\
", {arguments.first});")
1530 else if pname
== "object_id" then
1531 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
1533 else if pname
== "+" then
1534 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1536 else if pname
== "-" then
1537 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1539 else if pname
== "unary -" then
1540 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1542 else if pname
== "succ" then
1543 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1545 else if pname
== "prec" then
1546 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1548 else if pname
== "*" then
1549 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1551 else if pname
== "/" then
1552 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1554 else if pname
== "==" then
1555 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1557 else if pname
== "!=" then
1558 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1559 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1561 else if pname
== "<" then
1562 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1564 else if pname
== ">" then
1565 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1567 else if pname
== "<=" then
1568 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1570 else if pname
== ">=" then
1571 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1573 else if pname
== "to_i" then
1574 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
1577 else if cname
== "Char" then
1578 if pname
== "output" then
1579 v
.add
("printf(\"%c\
", {arguments.first});")
1581 else if pname
== "object_id" then
1582 v
.ret
(arguments
.first
)
1584 else if pname
== "==" then
1585 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1587 else if pname
== "!=" then
1588 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1589 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1591 else if pname
== "ascii" then
1592 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1595 else if cname
== "NativeString" then
1596 if pname
== "[]" then
1597 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1599 else if pname
== "[]=" then
1600 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1602 else if pname
== "copy_to" then
1603 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1605 else if pname
== "atoi" then
1606 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
1609 else if cname
== "NativeArray" then
1610 var elttype
= arguments
.first
.mtype
1611 if pname
== "[]" then
1612 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1614 else if pname
== "[]=" then
1615 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1617 else if pname
== "copy_to" then
1618 v
.add
("memcpy({arguments[1]},{arguments[0]},{arguments[2]}*sizeof({elttype.ctype}));")
1622 if pname
== "exit" then
1623 v
.add
("exit({arguments[1]});")
1625 else if pname
== "sys" then
1626 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
1628 else if pname
== "calloc_string" then
1629 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
1631 else if pname
== "calloc_array" then
1632 var elttype
= arguments
.first
.mtype
.supertype_to
(v
.compiler
.mainmodule
,arguments
.first
.mtype
.as(MClassType),v
.get_class
("ArrayCapable")).as(MGenericType).arguments
.first
1633 v
.ret
(v
.new_expr
("({elttype.ctype}*)GC_MALLOC({arguments[1]} * sizeof({elttype.ctype}))", ret
.as(not null)))
1635 else if pname
== "object_id" then
1636 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
1638 else if pname
== "is_same_type" then
1639 if arguments
[0].mtype
.ctype
== "val*" then
1640 v
.ret
(v
.new_expr
("{arguments[0]}->classid == {arguments[1]}->classid", ret
.as(not null)))
1642 v
.ret
(v
.new_expr
("{v.compiler.classid(arguments[0].mtype.as(MClassType))} == {arguments[1]}->classid", ret
.as(not null)))
1645 else if pname
== "output_class_name" then
1646 if arguments
[0].mtype
.ctype
== "val*" then
1647 v
.add
("printf(\"%s\\n\
", class_names[{arguments.first}->classid]);")
1649 v
.add
("printf(\"%s\\n\
", class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]);")
1652 else if pname
== "native_class_name" then
1653 if arguments
[0].mtype
.ctype
== "val*" then
1654 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{arguments.first}->classid]", ret
.as(not null)))
1656 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]", ret
.as(not null)))
1660 v
.add
("printf(\"Not implemented
{class_name}:{mpropdef} at
{location.to_s}\\n\
");")
1661 debug
("Not implemented {mpropdef}")
1665 redef class AExternMethPropdef
1666 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1669 var nextern
= self.n_extern
1670 if nextern
== null then
1671 debug
("{mpropdef} need extern name")
1674 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1675 if location
.file
!= null then
1676 var file
= location
.file
.filename
1677 v
.compiler
.add_extern
(file
)
1679 var res
: nullable RuntimeVariable = null
1680 var ret
= mpropdef
.msignature
.return_mtype
1682 ret
= v
.resolve_for
(ret
, arguments
.first
)
1683 res
= v
.new_var
(ret
)
1687 v
.add
("{externname}({arguments.join(", ")});")
1689 v
.add
("{res} = {externname}({arguments.join(", ")});")
1695 redef class AExternInitPropdef
1696 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1699 var nextern
= self.n_extern
1700 if nextern
== null then
1701 debug
("{mpropdef} need extern name")
1704 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1705 if location
.file
!= null then
1706 var file
= location
.file
.filename
1707 v
.compiler
.add_extern
(file
)
1709 var ret
= arguments
.first
.mtype
1710 var res
= v
.new_var
(ret
)
1714 v
.add
("{res} = {externname}({arguments.join(", ")});")
1719 redef class AAttrPropdef
1720 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1722 if arguments
.length
== 1 then
1723 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
1724 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
1726 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
1730 private fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
1732 var nexpr
= self.n_expr
1733 if nexpr
!= null then
1734 var old_frame
= v
.frame
1735 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
1737 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
1738 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
1744 redef class AClassdef
1745 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1747 if mpropdef
== self.mfree_init
then
1748 var super_inits
= self.super_inits
1749 if super_inits
!= null then
1750 assert arguments
.length
== 1
1751 for su
in super_inits
do
1752 v
.send
(su
, arguments
)
1756 var recv
= arguments
.first
1758 # Collect undefined attributes
1759 for npropdef
in self.n_propdefs
do
1760 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
1761 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
1772 # Try to compile self as an expression
1773 # Do not call this method directly, use `v.expr' instead
1774 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
1776 debug
("Unimplemented expr {class_name}")
1777 v
.add
("printf(\"Not implemented
{class_name}:{location.to_s}\\n\
");")
1778 var mtype
= self.mtype
1779 if mtype
== null then
1782 var res
= v
.new_var
(mtype
)
1783 v
.add
("/* {res} = NOT YET {class_name} */")
1788 # Try to compile self as a statement
1789 # Do not call this method directly, use `v.stmt' instead
1790 private fun stmt
(v
: GlobalCompilerVisitor)
1793 if res
!= null then v
.add
("{res};")
1798 redef class ABlockExpr
1801 for e
in self.n_expr
do
1807 redef class AVardeclExpr
1810 var variable
= self.variable
.as(not null)
1811 var ne
= self.n_expr
1813 var i
= v
.expr
(ne
, variable
.declared_type
)
1814 v
.assign
(v
.variable
(variable
), i
)
1819 redef class AVarExpr
1822 var res
= v
.variable
(self.variable
.as(not null))
1823 var mtype
= self.mtype
.as(not null)
1824 return v
.autoadapt
(res
, mtype
)
1828 redef class AVarAssignExpr
1831 var variable
= self.variable
.as(not null)
1832 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1833 v
.assign
(v
.variable
(variable
), i
)
1837 redef class AVarReassignExpr
1840 var variable
= self.variable
.as(not null)
1841 var vari
= v
.variable
(variable
)
1842 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1843 var res
= v
.send
(reassign_property
.mproperty
, [vari
, value
])
1845 v
.assign
(v
.variable
(variable
), res
)
1849 redef class ASelfExpr
1852 return v
.frame
.arguments
.first
1856 redef class AContinueExpr
1859 v
.add
("goto CONTINUE_{self.escapemark.object_id};")
1863 redef class ABreakExpr
1866 v
.add
("goto BREAK_{self.escapemark.object_id};")
1870 redef class AReturnExpr
1873 var nexpr
= self.n_expr
1874 if nexpr
!= null then
1875 var returnvar
= v
.frame
.returnvar
.as(not null)
1876 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
1877 v
.assign
(returnvar
, i
)
1879 v
.add
("goto {v.frame.returnlabel.as(not null)};")
1883 redef class AAbortExpr
1886 v
.add_abort
("Aborted")
1893 var cond
= v
.expr_bool
(self.n_expr
)
1894 v
.add
("if ({cond})\{")
1902 redef class AIfexprExpr
1905 var res
= v
.new_var
(self.mtype
.as(not null))
1906 var cond
= v
.expr_bool
(self.n_expr
)
1907 v
.add
("if ({cond})\{")
1908 v
.assign
(res
, v
.expr
(self.n_then
, null))
1910 v
.assign
(res
, v
.expr
(self.n_else
, null))
1919 v
.stmt
(self.n_block
)
1920 var escapemark
= self.escapemark
1921 if escapemark
!= null then
1922 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1927 redef class AWhileExpr
1931 var cond
= v
.expr_bool
(self.n_expr
)
1932 v
.add
("if (!{cond}) break;")
1933 v
.stmt
(self.n_block
)
1934 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1936 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1940 redef class ALoopExpr
1944 v
.stmt
(self.n_block
)
1945 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1947 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1951 redef class AForExpr
1954 var cl
= v
.expr
(self.n_expr
, null)
1955 var it
= v
.send
(v
.get_property
("iterator", cl
.mtype
), [cl
])
1958 var ok
= v
.send
(v
.get_property
("is_ok", it
.mtype
), [it
])
1960 v
.add
("if(!{ok}) break;")
1961 var i
= v
.send
(v
.get_property
("item", it
.mtype
), [it
])
1963 v
.assign
(v
.variable
(variables
.first
), i
)
1964 v
.stmt
(self.n_block
)
1965 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1966 v
.send
(v
.get_property
("next", it
.mtype
), [it
])
1968 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1972 redef class AAssertExpr
1975 var cond
= v
.expr_bool
(self.n_expr
)
1976 v
.add
("if (!{cond}) \{")
1980 v
.add_abort
("Assert '{nid.text}' failed")
1982 v
.add_abort
("Assert failed")
1991 var res
= v
.new_var
(self.mtype
.as(not null))
1992 var i1
= v
.expr_bool
(self.n_expr
)
1993 v
.add
("if ({i1}) \{")
1996 var i2
= v
.expr_bool
(self.n_expr2
)
1997 v
.add
("{res} = {i2};")
2003 redef class AAndExpr
2006 var res
= v
.new_var
(self.mtype
.as(not null))
2007 var i1
= v
.expr_bool
(self.n_expr
)
2008 v
.add
("if (!{i1}) \{")
2011 var i2
= v
.expr_bool
(self.n_expr2
)
2012 v
.add
("{res} = {i2};")
2018 redef class ANotExpr
2021 var cond
= v
.expr_bool
(self.n_expr
)
2022 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2026 redef class AOrElseExpr
2029 var res
= v
.new_var
(self.mtype
.as(not null))
2030 var i1
= v
.expr
(self.n_expr
, null)
2031 v
.add
("if ({i1}!=NULL) \{")
2034 var i2
= v
.expr
(self.n_expr2
, null)
2044 var value1
= v
.expr
(self.n_expr
, null)
2045 var value2
= v
.expr
(self.n_expr2
, null)
2046 return v
.equal_test
(value1
, value2
)
2050 redef class AIntExpr
2053 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2057 redef class AFloatExpr
2060 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2064 redef class ACharExpr
2067 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2071 redef class AArrayExpr
2074 var mtype
= self.mtype
.as(MGenericType).arguments
.first
2075 var array
= new Array[RuntimeVariable]
2076 for nexpr
in self.n_exprs
.n_exprs
do
2077 var i
= v
.expr
(nexpr
, mtype
)
2080 return v
.array_instance
(array
, mtype
)
2084 redef class AStringFormExpr
2087 return v
.string_instance
(self.value
.as(not null))
2091 redef class ASuperstringExpr
2094 var array
= new Array[RuntimeVariable]
2095 for ne
in self.n_exprs
do
2096 var i
= v
.expr
(ne
, null)
2099 var a
= v
.array_instance
(array
, v
.object_type
)
2100 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2105 redef class ACrangeExpr
2108 var i1
= v
.expr
(self.n_expr
, null)
2109 var i2
= v
.expr
(self.n_expr2
, null)
2110 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2111 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2112 v
.check_init_instance
(res
)
2117 redef class AOrangeExpr
2120 var i1
= v
.expr
(self.n_expr
, null)
2121 var i2
= v
.expr
(self.n_expr2
, null)
2122 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2123 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2124 v
.check_init_instance
(res
)
2129 redef class ATrueExpr
2132 return v
.new_expr
("1", self.mtype
.as(not null))
2136 redef class AFalseExpr
2139 return v
.new_expr
("0", self.mtype
.as(not null))
2143 redef class ANullExpr
2146 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2151 redef class AIsaExpr
2154 var i
= v
.expr
(self.n_expr
, null)
2155 return v
.type_test
(i
, self.cast_type
.as(not null))
2159 redef class AAsCastExpr
2162 var i
= v
.expr
(self.n_expr
, null)
2163 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2164 v
.add
("if (!{cond}) \{")
2165 v
.add_abort
("Cast failed")
2171 redef class AAsNotnullExpr
2174 var i
= v
.expr
(self.n_expr
, null)
2175 v
.add
("if ({i} == NULL) \{")
2176 v
.add_abort
("Cast failed")
2182 redef class AParExpr
2185 return v
.expr
(self.n_expr
, null)
2189 redef class AOnceExpr
2192 var mtype
= self.mtype
.as(not null)
2193 var name
= v
.get_name
("varonce")
2194 var guard
= v
.get_name
(name
+ "_guard")
2195 v
.add_decl
("static {mtype.ctype} {name};")
2196 v
.add_decl
("static int {guard};")
2197 var res
= v
.new_var
(mtype
)
2198 v
.add
("if ({guard}) \{")
2199 v
.add
("{res} = {name};")
2201 var i
= v
.expr
(self.n_expr
, mtype
)
2202 v
.add
("{res} = {i};")
2203 v
.add
("{name} = {res};")
2204 v
.add
("{guard} = 1;")
2210 redef class ASendExpr
2213 var recv
= v
.expr
(self.n_expr
, null)
2215 for a
in compute_raw_arguments
do
2216 args
.add
(v
.expr
(a
, null))
2218 var mproperty
= self.mproperty
.as(not null)
2219 return v
.send
(mproperty
, args
)
2223 redef class ASendReassignFormExpr
2226 var recv
= v
.expr
(self.n_expr
, null)
2228 for a
in compute_raw_arguments
do
2229 args
.add
(v
.expr
(a
, null))
2231 var value
= v
.expr
(self.n_value
, null)
2233 var mproperty
= self.mproperty
.as(not null)
2234 var left
= v
.send
(mproperty
, args
)
2237 var res
= v
.send
(reassign_property
.mproperty
, [left
, value
])
2241 v
.send
(self.write_mproperty
.as(not null), args
)
2245 redef class ASuperExpr
2248 var recv
= v
.frame
.arguments
.first
2250 for a
in self.n_args
.n_exprs
do
2251 args
.add
(v
.expr
(a
, null))
2253 if args
.length
== 1 then
2254 args
= v
.frame
.arguments
2257 var mproperty
= self.mproperty
2258 if mproperty
!= null then
2259 if mproperty
.intro
.msignature
.arity
== 0 then
2263 var res
= v
.send
(mproperty
, args
)
2267 # stantard call-next-method
2268 var mpropdef
= v
.frame
.mpropdef
2269 # FIXME: we do not want an ugly static call!
2270 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2271 if mpropdefs
.length
!= 1 then
2272 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2274 mpropdef
= mpropdefs
.first
2275 assert mpropdef
isa MMethodDef
2276 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2281 redef class ANewExpr
2284 var mproperty
= self.mproperty
.as(not null)
2285 var mtype
= self.mtype
.as(MClassType)
2287 var ctype
= mtype
.ctype
2288 if ctype
== "val*" then
2289 recv
= v
.init_instance
(mtype
)
2290 else if ctype
== "void*" then
2291 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2293 debug
("cannot new {mtype}")
2297 for a
in self.n_args
.n_exprs
do
2298 args
.add
(v
.expr
(a
, null))
2300 var res2
= v
.send
(mproperty
, args
)
2301 if res2
!= null then
2302 #self.debug("got {res2} from {mproperty}. drop {recv}")
2305 v
.check_init_instance
(recv
)
2310 redef class AAttrExpr
2313 var recv
= v
.expr
(self.n_expr
, null)
2314 var mproperty
= self.mproperty
.as(not null)
2315 return v
.read_attribute
(mproperty
, recv
)
2319 redef class AAttrAssignExpr
2322 var recv
= v
.expr
(self.n_expr
, null)
2323 var i
= v
.expr
(self.n_value
, null)
2324 var mproperty
= self.mproperty
.as(not null)
2325 v
.write_attribute
(mproperty
, recv
, i
)
2329 redef class AAttrReassignExpr
2332 var recv
= v
.expr
(self.n_expr
, null)
2333 var value
= v
.expr
(self.n_value
, null)
2334 var mproperty
= self.mproperty
.as(not null)
2335 var attr
= v
.read_attribute
(mproperty
, recv
)
2336 var res
= v
.send
(reassign_property
.mproperty
, [attr
, value
])
2338 v
.write_attribute
(mproperty
, recv
, res
)
2342 redef class AIssetAttrExpr
2345 redef class ADebugTypeExpr