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) and arguments.first.mtype == self.recv then
548 var frame = new Frame(v, self.mmethoddef, arguments.first, 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.compiler.todo(self)
564 v.add("{self.c_name}({arguments.join(",")});")
567 var res = v.new_var(ret)
568 v.add("{res} = {self.c_name}({arguments.join(",")});")
574 # A runtime variable hold a runtime value in C
575 # Runtime variables are associated to local variables and intermediate results
576 private class RuntimeVariable
577 # The name of the variable in the C code
580 # The static type of the variable (as declard in C)
583 # The current casted type of the variable (as known in Nit)
586 redef fun to_s do return name
589 # Visit the AST to generate the C code.
590 # Because of inlining, a visitor can visit more than one property.
591 private class GlobalCompilerVisitor
592 # The associated compiler
593 var compiler: GlobalCompiler
595 init(compiler: GlobalCompiler)
597 self.compiler = compiler
598 compiler.visitors.add(self)
601 # Alias for self.compiler.mainmodule.object_type
602 fun object_type: MClassType do return self.compiler.mainmodule.object_type
604 # Alias for self.compiler.mainmodule.bool_type
605 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
607 # Force to get the primitive class named `name' or abort
608 fun get_class
(name
: String): MClass
610 return self.compiler
.mainmodule
.get_primitive_class
(name
)
613 # Force to get the primitive property named `name' in the instance `recv' or abort
614 fun get_property
(name
: String, recv
: MType): MMethod
616 return self.compiler
.mainmodule
.force_get_primitive_method
(name
, recv
)
620 var frame
: nullable Frame
622 # Anchor a type to the main module and the current receiver
623 fun anchor
(mtype
: MType): MType
625 if not mtype
.need_anchor
then return mtype
626 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
627 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
.mtype
.as(MClassType))
630 # Add a line in the main part of the generated C
637 # (used for local or global declaration)
638 fun add_decl
(s
: String)
640 self.decl_lines
.add
(s
)
643 private var lines
: List[String] = new List[String]
644 private var decl_lines
: List[String] = new List[String]
646 # The current visited AST node
647 var current_node
: nullable AExpr = null
649 # Compile an expression an return its
650 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
652 var old
= self.current_node
653 self.current_node
= nexpr
654 var res
= nexpr
.expr
(self).as(not null)
655 if mtype
!= null then
656 mtype
= self.anchor
(mtype
)
657 res
= self.autobox
(res
, mtype
)
659 self.current_node
= old
663 # Unsafely cast a value to a new type
664 # ENSURE: return.name == value.name
665 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
667 mtype
= self.anchor
(mtype
)
668 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
671 var res
= new RuntimeVariable(value
.name
, value
.mtype
, mtype
)
676 # Box or unbox a value to another type iff a C type conversion is needed
677 # ENSURE: result.mtype.ctype == mtype.ctype
678 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
680 if value
.mtype
.ctype
== mtype
.ctype
then
682 else if value
.mtype
.ctype
== "val*" then
683 return self.new_expr
("((struct {mtype.c_name}*){value})->value /* autounbox from {value.mtype} to {mtype} */", mtype
)
684 else if mtype
.ctype
== "val*" then
685 var valtype
= value
.mtype
.as(MClassType)
686 var res
= self.new_var
(mtype
)
687 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
688 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
689 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
692 self.add
("{res} = GC_MALLOC(sizeof(struct {valtype.c_name})); /* autobox from {value.mtype} to {mtype} */")
693 self.add
("{res}->classid = {self.compiler.classid(valtype)};")
694 self.add
("((struct {valtype.c_name}*){res})->value = {value};")
697 # Bad things will append!
698 var res
= self.new_var
(mtype
)
699 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
700 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
705 # Correctly assign a left and a right value
706 # Boxing and unboxing is performed if required
707 fun assign
(left
, right
: RuntimeVariable)
709 right
= self.autobox
(right
, left
.mtype
)
710 self.add
("{left} = {right};")
714 # Alias for `self.expr(nexpr, self.bool_type)'
715 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
717 return expr
(nexpr
, bool_type
)
721 fun stmt
(nexpr
: nullable AExpr)
723 if nexpr
== null then return
724 var old
= self.current_node
725 self.current_node
= nexpr
727 self.current_node
= old
730 # Safely show a debug message on the current node and repeat the message in the C code
731 fun debug
(message
: String)
733 var node
= self.current_node
739 self.add
("/* DEBUG: {message} */")
742 # Return a new uninitialized local runtime_variable
743 fun new_var
(mtype
: MType): RuntimeVariable
745 if mtype
isa MNullType then
746 mtype
= self.object_type
748 mtype
= self.anchor
(mtype
)
750 var name
= self.get_name
("var")
751 var res
= new RuntimeVariable(name
, mtype
, mtype
)
752 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
756 # Return a new local runtime_variable initialized with the C expression `cexpr'.
757 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
759 var res
= new_var
(mtype
)
760 self.add
("{res} = {cexpr};")
764 # Return the local runtime_variable associated to a Nit local variable
765 fun variable
(variable
: Variable): RuntimeVariable
767 if self.variables
.has_key
(variable
) then
768 return self.variables
[variable
]
770 var name
= self.get_name
("var_{variable.name}")
771 var mtype
= variable
.declared_type
.as(not null)
772 mtype
= self.anchor
(mtype
)
773 var res
= new RuntimeVariable(name
, mtype
, mtype
)
774 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
775 self.variables
[variable
] = res
780 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
782 # Return a new name based on `s' and unique in the visitor
783 fun get_name
(s
: String): String
785 if not self.names
.has
(s
) then
789 var i
= self.last
+ 1
792 if not self.names
.has
(s2
) then
801 private var last
: Int = 0
803 private var names
: HashSet[String] = new HashSet[String]
805 # Generate a return with the value `s'
806 fun ret
(s
: RuntimeVariable)
808 self.assign
(self.frame
.returnvar
.as(not null), s
)
809 self.add
("goto {self.frame.returnlabel.as(not null)};")
812 # The runtime types that are acceptable for a given receiver.
813 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
815 var mtype
= recv
.mcasttype
816 var cache
= self.collect_types_cache
817 if cache
.has_key
(mtype
) then
820 var types
= new Array[MClassType]
821 var mainmodule
= self.compiler
.mainmodule
822 for t
in self.compiler
.runtime_type_analysis
.live_types
do
823 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
830 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
832 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
834 if not mtype
.need_anchor
then return mtype
835 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
836 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
.mtype
.as(MClassType), self.compiler
.mainmodule
, true)
840 # Generate a polymorphic send for the method `m' and the arguments `args'
841 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable
843 var types
= self.collect_types
(args
.first
)
845 var res
: nullable RuntimeVariable
846 var ret
= m
.intro
.msignature
.return_mtype
848 ret
= args
.first
.mtype
849 res
= self.new_var
(ret
)
850 else if ret
== null then
853 ret
= self.resolve_for
(ret
, args
.first
)
854 res
= self.new_var
(ret
)
857 if types
.is_empty
then
858 self.add
("/*BUG: no live types for {args.first.mtype} . {m}*/")
861 self.add
("/* send {m} on {args.first}: {args.first.mcasttype} (declared {args.first.mtype}) */")
862 if args
.first
.mtype
.ctype
!= "val*" then
863 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, args
.first
.mtype
)
864 if propdefs
.length
== 0 then
865 self.add
("/* skip {args.first.mcasttype}, no method {m} */")
868 assert propdefs
.length
== 1
869 var propdef
= propdefs
.first
870 var res2
= self.call
(propdef
, args
.first
.mtype
.as(MClassType), args
)
871 if res
!= null then self.assign
(res
, res2
.as(not null))
874 if args
.first
.mcasttype
isa MNullableType then
875 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
876 if m
.name
== "==" then
878 if args
[1].mcasttype
.ctype
== "val*" then
879 self.add
("{res} = ({args[1]} == NULL);")
881 self.add
("{res} = 0; /* {args[1]}: {args[1].mcasttype} cannot be null */")
883 else if m
.name
== "!=" then
885 if args
[1].mcasttype
.ctype
== "val*" then
886 self.add
("{res} = ({args[1]} != NULL);")
888 self.add
("{res} = 1; /* {args[1]}: {args[1].mcasttype} cannot be null */")
891 self.add_abort
("Reciever is null")
895 self.add
("switch({args.first}->classid) \{")
896 var defaultpropdef
: nullable MMethodDef = null
898 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
899 if propdefs
.length
== 0 then
900 self.add
("/* skip {t}, no method {m} */")
903 var propdef
= propdefs
.first
904 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
905 defaultpropdef
= propdef
908 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
909 var res2
= self.call
(propdef
, t
, args
)
910 if res
!= null then self.assign
(res
, res2
.as(not null))
913 if defaultpropdef
!= null then
914 self.add
("default: /* default is Object */")
915 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
916 if res
!= null then self.assign
(res
, res2
.as(not null))
918 self.add
("default: /* bug */")
919 self.bugtype
(args
.first
)
925 fun check_valid_reciever
(recvtype
: MClassType)
927 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
928 print
"{recvtype} is not a live type"
932 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
934 check_valid_reciever
(recvtype
)
935 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
936 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
937 recvtype
= m
.mclassdef
.bound_mtype
939 var ars
= new Array[RuntimeVariable]
940 var recv
= self.autobox
(args
.first
, recvtype
)
941 recv
= self.autoadapt
(recv
, recvtype
)
944 var vararg_rank
= m
.msignature
.vararg_rank
945 if vararg_rank
>= 0 then
946 assert args
.length
>= m
.msignature
.arity
+ 1 # because of self
948 args
= new Array[RuntimeVariable]
950 args
.add
(rawargs
.first
) # recv
952 for i
in [0..vararg_rank
[ do
953 args
.add
(rawargs
[i
+1])
956 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-m
.msignature
.arity
957 var vararg
= new Array[RuntimeVariable]
958 for i
in [vararg_rank
..vararg_lastrank
] do
959 vararg
.add
(rawargs
[i
+1])
961 # FIXME: its it to late to determine the vararg type, this should have been done during a previous analysis
962 var elttype
= m
.msignature
.parameter_mtypes
[vararg_rank
]
963 elttype
= self.resolve_for
(elttype
, recv
)
964 args
.add
(self.array_instance
(vararg
, elttype
))
966 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
967 args
.add
(rawargs
[i
+1])
970 assert args
.length
== m
.msignature
.arity
+ 1 # because of self
972 for i
in [0..m
.msignature
.arity
[ do
973 var t
= m
.msignature
.parameter_mtypes
[i
]
974 if i
== vararg_rank
then
977 t
= self.resolve_for
(t
, recv
)
978 ars
.add
(self.autobox
(args
[i
+1], t
))
980 var rm
= new RuntimeFunction(m
, recvtype
)
981 return rm
.call
(self, ars
)
984 fun bugtype
(recv
: RuntimeVariable)
986 if recv
.mtype
.ctype
!= "val*" then return
987 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
990 # Generate a polymorphic attribute read
991 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
993 var types
= self.collect_types
(recv
)
995 var ret
= a
.intro
.static_mtype
.as(not null)
996 ret
= self.resolve_for
(ret
, recv
)
997 var res
= self.new_var
(ret
)
999 if types
.is_empty
then
1000 self.add
("/*BUG: no live types for {recv.mtype} . {a}*/")
1003 self.add
("/* read {a} on {recv.mcasttype} */")
1004 self.add
("switch({recv}->classid) \{")
1006 self.add
("case {self.compiler.classid(t)}:")
1007 var recv2
= self.autoadapt
(recv
, t
)
1008 var ta
= a
.intro
.static_mtype
.as(not null)
1009 ta
= self.resolve_for
(ta
, recv2
)
1010 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1011 if not ta
isa MNullableType then
1012 if ta
.ctype
== "val*" then
1013 self.add
("if ({res2} == NULL) \{")
1014 self.add_abort
("Uninitialized attribute {a.name}")
1017 self.add
("/*NOTYET isset on primitive attributes*/")
1020 self.assign
(res
, res2
)
1023 self.add
("default: /* Bug */")
1030 # Generate a polymorphic attribute write
1031 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1033 var types
= self.collect_types
(recv
)
1035 if types
.is_empty
then
1036 self.add
("/*BUG: no live types for {recv.mtype} . {a}*/")
1039 self.add
("/* write {a} on {recv.mcasttype} */")
1040 self.add
("switch({recv}->classid) \{")
1042 self.add
("case {self.compiler.classid(t)}:")
1043 var recv2
= self.autoadapt
(recv
, t
)
1044 var ta
= a
.intro
.static_mtype
.as(not null)
1045 ta
= self.resolve_for
(ta
, recv2
)
1046 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1049 self.add
("default: /* Bug*/")
1054 # Generate a alloc-instance + init-attributes
1055 fun init_instance
(mtype
: MClassType): RuntimeVariable
1057 mtype
= self.anchor
(mtype
).as(MClassType)
1058 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1059 debug
"problem: {mtype} was detected dead"
1061 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1065 # Generate a polymorphic subtype test
1066 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1068 mtype
= self.anchor
(mtype
)
1069 var types
= self.collect_types
(value
)
1071 var res
= self.new_var
(bool_type
)
1073 self.add
("/* isa {mtype} on {value.mcasttype} */")
1074 if value
.mcasttype
isa MNullableType then
1075 self.add
("if ({value} == NULL) \{")
1076 if mtype
isa MNullableType then
1077 self.add
("{res} = 1; /* isa {mtype} */")
1079 self.add
("{res} = 0; /* not isa {mtype} */")
1081 self.add
("\} else ")
1083 self.add
("switch({value}->classid) \{")
1085 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1086 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1089 self.add
("{res} = 1;")
1091 self.add
("default:")
1092 self.add
("{res} = 0;")
1098 # Generate a Nit "is" for two runtime_variables
1099 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1101 var res
= self.new_var
(bool_type
)
1102 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1107 if value1
.mtype
.ctype
!= "val*" then
1108 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
1109 self.add
("{res} = {value1} == {value2};")
1110 else if value2
.mtype
.ctype
!= "val*" then
1111 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1113 var mtype1
= value1
.mtype
.as(MClassType)
1114 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1115 self.add
("if ({res}) \{")
1116 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1120 var s
= new Array[String]
1121 for t
in self.compiler
.live_primitive_types
do
1122 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1123 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1124 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1127 self.add
("{res} = {value1} == {value2};")
1129 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1135 # Generate a check-init-instance
1136 # TODO: is an empty stub currently
1137 fun check_init_instance
(recv
: RuntimeVariable)
1141 # Generate an integer value
1142 fun int_instance
(value
: Int): RuntimeVariable
1144 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1145 self.add
("{res} = {value};")
1149 # Generate an array value
1150 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1152 elttype
= self.anchor
(elttype
)
1153 var res
= self.init_instance
(self.get_class
("Array").get_mtype
([elttype
]))
1154 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1155 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1156 self.add
("{nat} = GC_MALLOC({array.length} * sizeof({elttype.ctype}));")
1157 for i
in [0..array
.length
[ do
1158 var r
= self.autobox
(array
[i
], elttype
)
1159 self.add
("{nat}[{i}] = {r};")
1161 var length
= self.int_instance
(array
.length
)
1162 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1163 self.check_init_instance
(res
)
1168 # Generate a string value
1169 fun string_instance
(string
: String): RuntimeVariable
1171 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1172 self.add
("{nat} = \"{string.escape_to_c}\
";")
1173 var res
= self.init_instance
(self.get_class
("String").mclass_type
)
1174 var length
= self.int_instance
(string
.length
)
1175 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1176 self.check_init_instance
(res
)
1180 # Generate generic abort
1181 # used by aborts, asserts, casts, etc.
1182 fun add_abort
(message
: String)
1184 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1185 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});")
1187 self.add
("fprintf(stderr, \"%s\\n\
", \"{message.escape_to_c}\
");")
1189 self.add
("exit(1);")
1193 # A frame correspond to a visited property in a GlobalCompilerVisitor
1195 # The associated visitor
1197 var visitor
: GlobalCompilerVisitor
1199 # The executed property.
1200 # A Method in case of a call, an attribute in case of a default initialization.
1201 var mpropdef
: MPropDef
1203 # The static type of the receiver
1204 var receiver
: RuntimeVariable
1206 # Arguments of the method (the first is the receiver)
1207 var arguments
: Array[RuntimeVariable]
1209 # The runtime_variable associated to the return (in a function)
1210 var returnvar
: nullable RuntimeVariable = null
1212 # The label at the end of the property
1213 var returnlabel
: nullable String = null
1216 redef class MPropDef
1217 private var c_name_cache
: nullable String
1219 # The mangled name associated to the property
1222 var res
= self.c_name_cache
1223 if res
!= null then return res
1224 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1225 self.c_name_cache
= res
1230 redef class MMethodDef
1231 # Can the body be inlined?
1232 private fun can_inline
(v
: GlobalCompilerVisitor): Bool
1234 var modelbuilder
= v
.compiler
.modelbuilder
1235 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1236 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1237 return npropdef
.can_inline
1238 else if self.mproperty
.name
== "init" then
1245 # Inline the body in another visitor
1246 private fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1248 var modelbuilder
= v
.compiler
.modelbuilder
1249 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1250 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1251 npropdef
.compile_to_c
(v
, self, arguments
)
1252 else if self.mproperty
.name
== "init" then
1253 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1254 nclassdef
.compile_to_c
(v
, self, arguments
)
1261 # Compile the body in a new visitor
1262 private fun compile_to_c
(compiler
: GlobalCompiler, modelbuilder
: ModelBuilder, recv
: MClassType)
1264 if not recv
.is_subtype
(compiler
.mainmodule
, null, self.mclassdef
.bound_mtype
) then
1265 print
("problem: why do we compile {self} for {recv}?")
1269 var v
= new GlobalCompilerVisitor(compiler
)
1270 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1271 var arguments
= new Array[RuntimeVariable]
1272 var frame
= new Frame(v
, self, selfvar
, arguments
)
1275 var sig
= new Buffer
1276 var comment
= new Buffer
1277 var ret
= self.msignature
.return_mtype
1279 ret
= v
.resolve_for
(ret
, selfvar
)
1280 sig
.append
("{ret.ctype} ")
1281 else if self.mproperty
.is_new
then
1283 sig
.append
("{ret.ctype} ")
1287 sig
.append
(self.c_name
)
1288 if recv
!= self.mclassdef
.bound_mtype
then
1289 sig
.append
("__{recv.c_name}")
1291 sig
.append
("({recv.ctype} self")
1292 comment
.append
("(self: {recv}")
1293 arguments
.add
(selfvar
)
1294 for i
in [0..self.msignature
.arity
[ do
1295 var mtype
= self.msignature
.parameter_mtypes
[i
]
1296 if i
== self.msignature
.vararg_rank
then
1297 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1299 mtype
= v
.resolve_for
(mtype
, selfvar
)
1300 comment
.append
(", {mtype}")
1301 sig
.append
(", {mtype.ctype} p{i}")
1302 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1303 arguments
.add
(argvar
)
1308 comment
.append
(": {ret}")
1310 compiler
.header
.add_decl
("{sig};")
1312 v
.add_decl
("/* method {self} for {comment} */")
1313 v
.add_decl
("{sig} \{")
1314 #v.add("printf(\"method {self} for {comment}\\n\");")
1316 frame
.returnvar
= v
.new_var
(ret
)
1318 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1320 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1321 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1322 npropdef
.compile_to_c
(v
, self, arguments
)
1323 else if self.mproperty
.name
== "init" then
1324 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1325 nclassdef
.compile_to_c
(v
, self, arguments
)
1330 v
.add
("{frame.returnlabel.as(not null)}:;")
1332 v
.add
("return {frame.returnvar.as(not null)};")
1338 redef class APropdef
1339 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1341 v
.add
("printf(\"Not implemented
{class_name} {mpropdef} at
{location.to_s}\\n\
");")
1342 debug
("Not yet implemented")
1345 private fun can_inline
: Bool do return true
1348 redef class AConcreteMethPropdef
1349 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1351 for i
in [0..mpropdef
.msignature
.arity
[ do
1352 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1353 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1355 # Call the implicit super-init
1356 var auto_super_inits
= self.auto_super_inits
1357 if auto_super_inits
!= null then
1358 var selfarg
= [arguments
.first
]
1359 for auto_super_init
in auto_super_inits
do
1360 if auto_super_init
.intro
.msignature
.arity
== 0 then
1361 v
.send
(auto_super_init
, selfarg
)
1363 v
.send
(auto_super_init
, arguments
)
1368 v
.stmt
(self.n_block
)
1371 redef fun can_inline
1373 if self.auto_super_inits
!= null then return false
1374 var nblock
= self.n_block
1375 if nblock
== null then return true
1376 #if nblock isa ABlockExpr and nblock.n_expr.length == 1 then return true
1381 redef class AInternMethPropdef
1382 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1384 var pname
= mpropdef
.mproperty
.name
1385 var cname
= mpropdef
.mclassdef
.mclass
.name
1386 var ret
= mpropdef
.msignature
.return_mtype
1388 ret
= v
.resolve_for
(ret
, arguments
.first
)
1390 if cname
== "Int" then
1391 if pname
== "output" then
1392 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1394 else if pname
== "object_id" then
1395 v
.ret
(arguments
.first
)
1397 else if pname
== "+" then
1398 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1400 else if pname
== "-" then
1401 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1403 else if pname
== "unary -" then
1404 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1406 else if pname
== "succ" then
1407 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1409 else if pname
== "prec" then
1410 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1412 else if pname
== "*" then
1413 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1415 else if pname
== "/" then
1416 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1418 else if pname
== "%" then
1419 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1421 else if pname
== "lshift" then
1422 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1424 else if pname
== "rshift" then
1425 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1427 else if pname
== "==" then
1428 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1430 else if pname
== "!=" then
1431 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1432 v
.ret
(v
.new_expr
("!{res}", 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
== "<=" then
1441 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1443 else if pname
== ">=" then
1444 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1446 else if pname
== "to_f" then
1447 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1449 else if pname
== "ascii" then
1450 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1453 else if cname
== "Char" then
1454 if pname
== "output" then
1455 v
.add
("printf(\"%c\
", {arguments.first});")
1457 else if pname
== "object_id" then
1458 v
.ret
(arguments
.first
)
1460 else if pname
== "==" then
1461 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1463 else if pname
== "!=" then
1464 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1465 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1467 else if pname
== "succ" then
1468 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1470 else if pname
== "prec" then
1471 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1473 else if pname
== "<" then
1474 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1476 else if pname
== ">" then
1477 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1479 else if pname
== "<=" then
1480 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1482 else if pname
== ">=" then
1483 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1485 else if pname
== "to_i" then
1486 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
1488 else if pname
== "ascii" then
1489 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
1492 else if cname
== "Bool" then
1493 if pname
== "output" then
1494 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
1496 else if pname
== "object_id" then
1497 v
.ret
(arguments
.first
)
1499 else if pname
== "==" then
1500 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1502 else if pname
== "!=" then
1503 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1504 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1507 else if cname
== "Float" then
1508 if pname
== "output" then
1509 v
.add
("printf(\"%f\\n\
", {arguments.first});")
1511 else if pname
== "object_id" then
1512 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
1514 else if pname
== "+" then
1515 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1517 else if pname
== "-" then
1518 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1520 else if pname
== "unary -" then
1521 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1523 else if pname
== "succ" then
1524 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1526 else if pname
== "prec" then
1527 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1529 else if pname
== "*" then
1530 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1532 else if pname
== "/" then
1533 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1535 else if pname
== "==" then
1536 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1538 else if pname
== "!=" then
1539 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1540 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1542 else if pname
== "<" then
1543 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1545 else if pname
== ">" then
1546 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[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
== "to_i" then
1555 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
1558 else if cname
== "Char" then
1559 if pname
== "output" then
1560 v
.add
("printf(\"%c\
", {arguments.first});")
1562 else if pname
== "object_id" then
1563 v
.ret
(arguments
.first
)
1565 else if pname
== "==" then
1566 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1568 else if pname
== "!=" then
1569 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1570 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1572 else if pname
== "ascii" then
1573 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1576 else if cname
== "NativeString" then
1577 if pname
== "[]" then
1578 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1580 else if pname
== "[]=" then
1581 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1583 else if pname
== "copy_to" then
1584 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1586 else if pname
== "atoi" then
1587 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
1590 else if cname
== "NativeArray" then
1591 var elttype
= arguments
.first
.mtype
1592 if pname
== "[]" then
1593 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1595 else if pname
== "[]=" then
1596 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1598 else if pname
== "copy_to" then
1599 v
.add
("memcpy({arguments[1]},{arguments[0]},{arguments[2]}*sizeof({elttype.ctype}));")
1603 if pname
== "exit" then
1604 v
.add
("exit({arguments[1]});")
1606 else if pname
== "sys" then
1607 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
1609 else if pname
== "calloc_string" then
1610 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
1612 else if pname
== "calloc_array" then
1613 var elttype
= arguments
.first
.mtype
.supertype_to
(v
.compiler
.mainmodule
,arguments
.first
.mtype
.as(MClassType),v
.get_class
("ArrayCapable")).as(MGenericType).arguments
.first
1614 v
.ret
(v
.new_expr
("({elttype.ctype}*)GC_MALLOC({arguments[1]} * sizeof({elttype.ctype}))", ret
.as(not null)))
1616 else if pname
== "object_id" then
1617 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
1619 else if pname
== "is_same_type" then
1620 if arguments
[0].mtype
.ctype
== "val*" then
1621 v
.ret
(v
.new_expr
("{arguments[0]}->classid == {arguments[1]}->classid", ret
.as(not null)))
1623 v
.ret
(v
.new_expr
("{v.compiler.classid(arguments[0].mtype.as(MClassType))} == {arguments[1]}->classid", ret
.as(not null)))
1626 else if pname
== "output_class_name" then
1627 if arguments
[0].mtype
.ctype
== "val*" then
1628 v
.add
("printf(\"%s\\n\
", class_names[{arguments.first}->classid]);")
1630 v
.add
("printf(\"%s\\n\
", class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]);")
1633 else if pname
== "native_class_name" then
1634 if arguments
[0].mtype
.ctype
== "val*" then
1635 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{arguments.first}->classid]", ret
.as(not null)))
1637 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]", ret
.as(not null)))
1641 v
.add
("printf(\"Not implemented
{class_name}:{mpropdef} at
{location.to_s}\\n\
");")
1642 debug
("Not implemented {mpropdef}")
1646 redef class AExternMethPropdef
1647 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1650 var nextern
= self.n_extern
1651 if nextern
== null then
1652 debug
("{mpropdef} need extern name")
1655 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1656 if location
.file
!= null then
1657 var file
= location
.file
.filename
1658 v
.compiler
.add_extern
(file
)
1660 var res
: nullable RuntimeVariable = null
1661 var ret
= mpropdef
.msignature
.return_mtype
1663 ret
= v
.resolve_for
(ret
, arguments
.first
)
1664 res
= v
.new_var
(ret
)
1668 v
.add
("{externname}({arguments.join(", ")});")
1670 v
.add
("{res} = {externname}({arguments.join(", ")});")
1676 redef class AExternInitPropdef
1677 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1680 var nextern
= self.n_extern
1681 if nextern
== null then
1682 debug
("{mpropdef} need extern name")
1685 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1686 if location
.file
!= null then
1687 var file
= location
.file
.filename
1688 v
.compiler
.add_extern
(file
)
1690 var ret
= arguments
.first
.mtype
1691 var res
= v
.new_var
(ret
)
1695 v
.add
("{res} = {externname}({arguments.join(", ")});")
1700 redef class AAttrPropdef
1701 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1703 if arguments
.length
== 1 then
1704 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
1705 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
1707 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
1711 private fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
1713 var nexpr
= self.n_expr
1714 if nexpr
!= null then
1715 var old_frame
= v
.frame
1716 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
, [recv
])
1718 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
1719 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
1725 redef class AClassdef
1726 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1728 if mpropdef
== self.mfree_init
then
1729 var super_inits
= self.super_inits
1730 if super_inits
!= null then
1731 assert arguments
.length
== 1
1732 for su
in super_inits
do
1733 v
.send
(su
, arguments
)
1737 var recv
= arguments
.first
1739 # Collect undefined attributes
1740 for npropdef
in self.n_propdefs
do
1741 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
1742 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
1753 # Try to compile self as an expression
1754 # Do not call this method directly, use `v.expr' instead
1755 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
1757 debug
("Unimplemented expr {class_name}")
1758 v
.add
("printf(\"Not implemented
{class_name}:{location.to_s}\\n\
");")
1759 var mtype
= self.mtype
1760 if mtype
== null then
1763 var res
= v
.new_var
(mtype
)
1764 v
.add
("/* {res} = NOT YET {class_name} */")
1769 # Try to compile self as a statement
1770 # Do not call this method directly, use `v.stmt' instead
1771 private fun stmt
(v
: GlobalCompilerVisitor)
1774 if res
!= null then v
.add
("{res};")
1779 redef class ABlockExpr
1782 for e
in self.n_expr
do
1788 redef class AVardeclExpr
1791 var variable
= self.variable
.as(not null)
1792 var ne
= self.n_expr
1794 var i
= v
.expr
(ne
, variable
.declared_type
)
1795 v
.assign
(v
.variable
(variable
), i
)
1800 redef class AVarExpr
1803 var res
= v
.variable
(self.variable
.as(not null))
1804 var mtype
= self.mtype
.as(not null)
1805 return v
.autoadapt
(res
, mtype
)
1809 redef class AVarAssignExpr
1812 var variable
= self.variable
.as(not null)
1813 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1814 v
.assign
(v
.variable
(variable
), i
)
1818 redef class AVarReassignExpr
1821 var variable
= self.variable
.as(not null)
1822 var vari
= v
.variable
(variable
)
1823 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1824 var res
= v
.send
(reassign_property
.mproperty
, [vari
, value
])
1826 v
.assign
(v
.variable
(variable
), res
)
1830 redef class ASelfExpr
1833 return v
.frame
.receiver
1837 redef class AContinueExpr
1840 v
.add
("goto CONTINUE_{self.escapemark.object_id};")
1844 redef class ABreakExpr
1847 v
.add
("goto BREAK_{self.escapemark.object_id};")
1851 redef class AReturnExpr
1854 var nexpr
= self.n_expr
1855 if nexpr
!= null then
1856 var returnvar
= v
.frame
.returnvar
.as(not null)
1857 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
1858 v
.assign
(returnvar
, i
)
1860 v
.add
("goto {v.frame.returnlabel.as(not null)};")
1864 redef class AAbortExpr
1867 v
.add_abort
("Aborted")
1874 var cond
= v
.expr_bool
(self.n_expr
)
1875 v
.add
("if ({cond})\{")
1883 redef class AIfexprExpr
1886 var res
= v
.new_var
(self.mtype
.as(not null))
1887 var cond
= v
.expr_bool
(self.n_expr
)
1888 v
.add
("if ({cond})\{")
1889 v
.assign
(res
, v
.expr
(self.n_then
, null))
1891 v
.assign
(res
, v
.expr
(self.n_else
, null))
1900 v
.stmt
(self.n_block
)
1901 var escapemark
= self.escapemark
1902 if escapemark
!= null then
1903 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1908 redef class AWhileExpr
1912 var cond
= v
.expr_bool
(self.n_expr
)
1913 v
.add
("if (!{cond}) break;")
1914 v
.stmt
(self.n_block
)
1915 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1917 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1921 redef class ALoopExpr
1925 v
.stmt
(self.n_block
)
1926 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1928 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1932 redef class AForExpr
1935 var cl
= v
.expr
(self.n_expr
, null)
1936 var it
= v
.send
(v
.get_property
("iterator", cl
.mtype
), [cl
])
1939 var ok
= v
.send
(v
.get_property
("is_ok", it
.mtype
), [it
])
1941 v
.add
("if(!{ok}) break;")
1942 var i
= v
.send
(v
.get_property
("item", it
.mtype
), [it
])
1944 v
.assign
(v
.variable
(variables
.first
), i
)
1945 v
.stmt
(self.n_block
)
1946 v
.add
("CONTINUE_{escapemark.object_id}: (void)0;")
1947 v
.send
(v
.get_property
("next", it
.mtype
), [it
])
1949 v
.add
("BREAK_{escapemark.object_id}: (void)0;")
1953 redef class AAssertExpr
1956 var cond
= v
.expr_bool
(self.n_expr
)
1957 v
.add
("if (!{cond}) \{")
1961 v
.add_abort
("Assert '{nid.text}' failed")
1963 v
.add_abort
("Assert failed")
1972 var res
= v
.new_var
(self.mtype
.as(not null))
1973 var i1
= v
.expr_bool
(self.n_expr
)
1974 v
.add
("if ({i1}) \{")
1977 var i2
= v
.expr_bool
(self.n_expr2
)
1978 v
.add
("{res} = {i2};")
1984 redef class AAndExpr
1987 var res
= v
.new_var
(self.mtype
.as(not null))
1988 var i1
= v
.expr_bool
(self.n_expr
)
1989 v
.add
("if (!{i1}) \{")
1992 var i2
= v
.expr_bool
(self.n_expr2
)
1993 v
.add
("{res} = {i2};")
1999 redef class ANotExpr
2002 var cond
= v
.expr_bool
(self.n_expr
)
2003 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2007 redef class AOrElseExpr
2010 var res
= v
.new_var
(self.mtype
.as(not null))
2011 var i1
= v
.expr
(self.n_expr
, null)
2012 v
.add
("if ({i1}!=NULL) \{")
2015 var i2
= v
.expr
(self.n_expr2
, null)
2025 var value1
= v
.expr
(self.n_expr
, null)
2026 var value2
= v
.expr
(self.n_expr2
, null)
2027 return v
.equal_test
(value1
, value2
)
2031 redef class AIntExpr
2034 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2038 redef class AFloatExpr
2041 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2045 redef class ACharExpr
2048 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2052 redef class AArrayExpr
2055 var mtype
= self.mtype
.as(MGenericType).arguments
.first
2056 var array
= new Array[RuntimeVariable]
2057 for nexpr
in self.n_exprs
.n_exprs
do
2058 var i
= v
.expr
(nexpr
, mtype
)
2061 return v
.array_instance
(array
, mtype
)
2065 redef class AStringFormExpr
2068 return v
.string_instance
(self.value
.as(not null))
2072 redef class ASuperstringExpr
2075 var array
= new Array[RuntimeVariable]
2076 for ne
in self.n_exprs
do
2077 var i
= v
.expr
(ne
, null)
2080 var a
= v
.array_instance
(array
, v
.object_type
)
2081 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2086 redef class ACrangeExpr
2089 var i1
= v
.expr
(self.n_expr
, null)
2090 var i2
= v
.expr
(self.n_expr2
, null)
2091 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2092 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2093 v
.check_init_instance
(res
)
2098 redef class AOrangeExpr
2101 var i1
= v
.expr
(self.n_expr
, null)
2102 var i2
= v
.expr
(self.n_expr2
, null)
2103 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2104 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2105 v
.check_init_instance
(res
)
2110 redef class ATrueExpr
2113 return v
.new_expr
("1", self.mtype
.as(not null))
2117 redef class AFalseExpr
2120 return v
.new_expr
("0", self.mtype
.as(not null))
2124 redef class ANullExpr
2127 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2132 redef class AIsaExpr
2135 var i
= v
.expr
(self.n_expr
, null)
2136 return v
.type_test
(i
, self.cast_type
.as(not null))
2140 redef class AAsCastExpr
2143 var i
= v
.expr
(self.n_expr
, null)
2144 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2145 v
.add
("if (!{cond}) \{")
2146 v
.add_abort
("Cast failed")
2152 redef class AAsNotnullExpr
2155 var i
= v
.expr
(self.n_expr
, null)
2156 v
.add
("if ({i} == NULL) \{")
2157 v
.add_abort
("Cast failed")
2163 redef class AParExpr
2166 return v
.expr
(self.n_expr
, null)
2170 redef class AOnceExpr
2173 var mtype
= self.mtype
.as(not null)
2174 var name
= v
.get_name
("varonce")
2175 var guard
= v
.get_name
(name
+ "_guard")
2176 v
.add_decl
("static {mtype.ctype} {name};")
2177 v
.add_decl
("static int {guard};")
2178 var res
= v
.new_var
(mtype
)
2179 v
.add
("if ({guard}) \{")
2180 v
.add
("{res} = {name};")
2182 var i
= v
.expr
(self.n_expr
, mtype
)
2183 v
.add
("{res} = {i};")
2184 v
.add
("{name} = {res};")
2185 v
.add
("{guard} = 1;")
2191 redef class ASendExpr
2194 var recv
= v
.expr
(self.n_expr
, null)
2196 for a
in compute_raw_arguments
do
2197 args
.add
(v
.expr
(a
, null))
2199 var mproperty
= self.mproperty
.as(not null)
2200 return v
.send
(mproperty
, args
)
2204 redef class ASendReassignFormExpr
2207 var recv
= v
.expr
(self.n_expr
, null)
2209 for a
in compute_raw_arguments
do
2210 args
.add
(v
.expr
(a
, null))
2212 var value
= v
.expr
(self.n_value
, null)
2214 var mproperty
= self.mproperty
.as(not null)
2215 var left
= v
.send
(mproperty
, args
)
2218 var res
= v
.send
(reassign_property
.mproperty
, [left
, value
])
2222 v
.send
(self.write_mproperty
.as(not null), args
)
2226 redef class ASuperExpr
2229 var recv
= v
.frame
.arguments
.first
2231 for a
in self.n_args
.n_exprs
do
2232 args
.add
(v
.expr
(a
, null))
2234 if args
.length
== 1 then
2235 args
= v
.frame
.arguments
2238 var mproperty
= self.mproperty
2239 if mproperty
!= null then
2240 if mproperty
.intro
.msignature
.arity
== 0 then
2244 var res
= v
.send
(mproperty
, args
)
2248 # stantard call-next-method
2249 var mpropdef
= v
.frame
.mpropdef
2250 # FIXME: we do not want an ugly static call!
2251 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2252 if mpropdefs
.length
!= 1 then
2253 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2255 mpropdef
= mpropdefs
.first
2256 assert mpropdef
isa MMethodDef
2257 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2262 redef class ANewExpr
2265 var mproperty
= self.mproperty
.as(not null)
2266 var mtype
= self.mtype
.as(MClassType)
2268 var ctype
= mtype
.ctype
2269 if ctype
== "val*" then
2270 recv
= v
.init_instance
(mtype
)
2271 else if ctype
== "void*" then
2272 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2274 debug
("cannot new {mtype}")
2278 for a
in self.n_args
.n_exprs
do
2279 args
.add
(v
.expr
(a
, null))
2281 var res2
= v
.send
(mproperty
, args
)
2282 if res2
!= null then
2283 #self.debug("got {res2} from {mproperty}. drop {recv}")
2286 v
.check_init_instance
(recv
)
2291 redef class AAttrExpr
2294 var recv
= v
.expr
(self.n_expr
, null)
2295 var mproperty
= self.mproperty
.as(not null)
2296 return v
.read_attribute
(mproperty
, recv
)
2300 redef class AAttrAssignExpr
2303 var recv
= v
.expr
(self.n_expr
, null)
2304 var i
= v
.expr
(self.n_value
, null)
2305 var mproperty
= self.mproperty
.as(not null)
2306 v
.write_attribute
(mproperty
, recv
, i
)
2310 redef class AAttrReassignExpr
2313 var recv
= v
.expr
(self.n_expr
, null)
2314 var value
= v
.expr
(self.n_value
, null)
2315 var mproperty
= self.mproperty
.as(not null)
2316 var attr
= v
.read_attribute
(mproperty
, recv
)
2317 var res
= v
.send
(reassign_property
.mproperty
, [attr
, value
])
2319 v
.write_attribute
(mproperty
, recv
, res
)
2323 redef class AIssetAttrExpr
2326 redef class ADebugTypeExpr