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")
39 var opt_hardening
: OptionBool = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
41 # --no-check-covariance
42 var opt_no_check_covariance
: OptionBool = new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
44 # --no-check-initialization
45 var opt_no_check_initialization
: OptionBool = new OptionBool("Disable isset tests at the end of constructors (dangerous)", "--no-check-initialization")
48 var opt_no_check_assert
: OptionBool = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
51 var opt_no_check_other
: OptionBool = new OptionBool("Disable implicit tests: unset attribute, null receiver (dangerous)", "--no-check-other")
56 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_hardening
)
57 self.option_context
.add_option
(self.opt_no_check_covariance
, self.opt_no_check_initialization
, self.opt_no_check_assert
, self.opt_no_check_other
)
61 redef class ModelBuilder
62 # Entry point to performs a global compilation on the AST of a complete program.
63 # `mainmodule` is the main module of the program
64 # `runtime_type_analysis` is a already computer type analysis.
65 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
68 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
70 var compiler
= new GlobalCompiler(mainmodule
, runtime_type_analysis
, self)
71 var v
= compiler
.new_visitor
73 v
.add_decl
("#include <stdlib.h>")
74 v
.add_decl
("#include <stdio.h>")
75 v
.add_decl
("#include <string.h>")
77 # TODO: Better way to activate the GC
78 v
.add_decl
("#include <gc/gc.h>")
79 #v.add_decl("#define GC_MALLOC(x) calloc(1, (x))")
81 # Declaration of structures the live Nit types
82 # Each live type is generated as an independent C `struct' type.
83 # They only share a common first field `classid` used to implement the polymorphism.
84 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val' that contains only the `classid` field.
86 v
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
87 for t
in runtime_type_analysis
.live_types
do
88 compiler
.declare_runtimeclass
(v
, t
)
91 # Global variable used by the legacy native interface
93 v
.add_decl
("extern int glob_argc;")
94 v
.add_decl
("extern char **glob_argv;")
95 v
.add_decl
("extern val *glob_sys;")
97 # Class names (for the class_name and output_class_name methods)
99 v
.add_decl
("extern const char const * class_names[];")
100 v
.add
("const char const * class_names[] = \{")
101 for t
in runtime_type_analysis
.live_types
do
102 v
.add
("\"{t}\
", /* {compiler.classid(t)} */")
107 # Init instance code (allocate and init-arguments)
109 for t
in runtime_type_analysis
.live_types
do
110 if t
.ctype
== "val*" then
111 compiler
.generate_init_instance
(t
)
112 compiler
.generate_check_init_instance
(t
)
114 compiler
.generate_box_instance
(t
)
118 # The main function of the C
119 compiler
.compile_main_function
121 # Compile until all runtime_functions are visited
123 while not compiler
.todos
.is_empty
do
124 var m
= compiler
.todos
.shift
125 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
126 m
.compile_to_c
(compiler
)
128 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
131 self.toolcontext
.info
("*** END VISITING: {time1-time0} ***", 2)
132 write_and_make
(compiler
)
135 protected fun write_and_make
(compiler
: GlobalCompiler)
137 var mainmodule
= compiler
.mainmodule
139 # Generate the .h and .c files
140 # A single C file regroups many compiled rumtime functions
141 # Note that we do not try to be clever an a small change in a Nit source file may change the content of all the generated .c files
144 var outname
= self.toolcontext
.opt_output
.value
145 if outname
== null then
146 outname
= "{mainmodule.name}.bin"
149 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
150 var h
= new OFStream.open
(hfilename
)
151 for l
in compiler
.header
.decl_lines
do
157 var cfiles
= new Array[String]
159 var file
: nullable OFStream = null
164 for vis
in compiler
.visitors
do
165 count
+= vis
.lines
.length
166 if file
== null or count
> 10000 then
168 if file
!= null then file
.close
169 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
170 cfiles
.add
(cfilename
)
171 file
= new OFStream.open
(cfilename
)
172 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
173 count
= vis
.lines
.length
175 if vis
!= compiler
.header
then
176 for l
in vis
.decl_lines
do
181 for l
in vis
.lines
do
186 if file
!= null then file
.close
188 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
190 # Generate the Makefile
192 var makename
= ".nit_compile/{mainmodule.name}.mk"
193 var makefile
= new OFStream.open
(makename
)
195 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
196 makefile
.write
("all: {outname}\n\n")
198 var ofiles
= new Array[String]
199 # Compile each generated file
201 var o
= f
.strip_extension
(".c") + ".o"
202 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
205 # Compile each required extern body into a specific .o
206 for f
in compiler
.extern_bodies
do
208 var o
= ".nit_compile/{mainmodule.name}.{i}.o"
209 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
213 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
215 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
217 self.toolcontext
.info
("Generated makefile: {makename}", 2)
220 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
222 # Execute the Makefile
224 if self.toolcontext
.opt_no_cc
.value
then return
227 self.toolcontext
.info
("*** COMPILING C ***", 1)
228 self.toolcontext
.info
("make -B -f {makename} -j 4", 2)
231 if self.toolcontext
.verbose_level
>= 3 then
232 res
= sys
.system
("make -B -f {makename} -j 4 2>&1")
234 res
= sys
.system
("make -B -f {makename} -j 4 2>&1 >/dev/null")
237 toolcontext
.error
(null, "make failed! Error code: {res}.")
241 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
245 # Singleton that store the knowledge about the compilation process
247 # The main module of the program
248 var mainmodule
: MModule
250 # The result of the RTA (used to know live types and methods)
251 var runtime_type_analysis
: RapidTypeAnalysis
253 # The modeulbuilder used to know the model and the AST
254 var modelbuilder
: ModelBuilder
256 # Is hardening asked? (see --hardening)
257 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
259 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, modelbuilder
: ModelBuilder)
261 self.mainmodule
= mainmodule
262 self.runtime_type_analysis
= runtime_type_analysis
263 self.modelbuilder
= modelbuilder
264 self.live_primitive_types
= new Array[MClassType]
265 for t
in runtime_type_analysis
.live_types
do
266 if t
.ctype
!= "val*" then
267 self.live_primitive_types
.add
(t
)
272 # Subset of runtime_type_analysis.live_types that contains only primitive types
273 # Used to implement the equal test
274 var live_primitive_types
: Array[MClassType]
276 # runtime_functions that need to be compiled
277 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
279 # runtime_functions already seen (todo or done)
280 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
281 fun todo
(m
: AbstractRuntimeFunction)
283 if seen
.has
(m
) then return
288 # Where global declaration are stored (the main .h)
290 # FIXME: should not be a vistor but just somewhere to store lines
291 # FIXME: should not have a global .h since it does not help recompilations
292 var header
: nullable GlobalCompilerVisitor writable = null
294 # The list of all associated visitors
295 # Used to generate .c files
296 # FIXME: should not be vistors but just somewhere to store lines
297 private var visitors
: List[GlobalCompilerVisitor] = new List[GlobalCompilerVisitor]
299 # List of additional .c files required to compile (native interface)
300 var extern_bodies
= new ArraySet[String]
302 # Return the C symbol associated to a live type runtime
303 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
304 fun classid
(mtype
: MClassType): String
306 if self.classids
.has_key
(mtype
) then
307 return self.classids
[mtype
]
309 print
"No classid for {mtype}"
313 # Cache for classid (computed by declare_runtimeclass)
314 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
316 # Declare C structures and identifiers for a runtime class
317 fun declare_runtimeclass
(v
: GlobalCompilerVisitor, mtype
: MClassType)
319 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
320 v
.add_decl
("/* runtime class {mtype} */")
321 var idnum
= classids
.length
322 var idname
= "ID_" + mtype
.c_name
323 self.classids
[mtype
] = idname
324 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
326 v
.add_decl
("struct {mtype.c_name} \{")
327 v
.add_decl
("int classid; /* must be {idname} */")
329 if mtype
.mclass
.name
== "NativeArray" then
330 # NativeArrays are just a instance header followed by an array of values
331 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
334 if mtype
.ctype
!= "val*" then
335 # Is the Nit type is native then the struct is a box with two fields:
336 # * the `classid` to be polymorph
337 # * the `value` that contains the native value.
338 v
.add_decl
("{mtype.ctype} value;")
341 # Collect all attributes and associate them a field in the structure.
342 # Note: we do not try to optimize the order and helps CC to optimize the client code.
343 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
344 for p
in cd
.intro_mproperties
do
345 if not p
isa MAttribute then continue
346 var t
= p
.intro
.static_mtype
.as(not null)
347 t
= t
.anchor_to
(self.mainmodule
, mtype
)
348 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
354 # Generate the init-instance of a live type (allocate + init-instance)
355 fun generate_init_instance
(mtype
: MClassType)
357 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
358 assert mtype
.ctype
== "val*"
359 var v
= self.new_visitor
361 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
364 if is_native_array
then
370 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
371 v
.add_decl
("/* allocate {mtype} */")
372 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
373 var res
= v
.new_var
(mtype
)
375 if is_native_array
then
376 var mtype_elt
= mtype
.arguments
.first
377 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
379 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
381 v
.add
("{res}->classid = {self.classid(mtype)};")
383 self.generate_init_attr
(v
, res
, mtype
)
384 v
.add
("return {res};")
388 fun generate_check_init_instance
(mtype
: MClassType)
390 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
392 var v
= self.new_visitor
393 var res
= new RuntimeVariable("self", mtype
, mtype
)
394 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
395 v
.add_decl
("/* allocate {mtype} */")
396 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
397 self.generate_check_attr
(v
, res
, mtype
)
401 # Generate code that collect initialize the attributes on a new instance
402 fun generate_init_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
404 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
406 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
407 for npropdef
in n
.n_propdefs
do
408 if npropdef
isa AAttrPropdef then
409 npropdef
.init_expr
(v
, recv
)
415 # Generate a check-init-instance
416 fun generate_check_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
418 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
420 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
421 for npropdef
in n
.n_propdefs
do
422 if npropdef
isa AAttrPropdef then
423 npropdef
.check_expr
(v
, recv
)
429 fun generate_box_instance
(mtype
: MClassType)
431 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
432 assert mtype
.ctype
!= "val*"
433 var v
= self.new_visitor
435 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
436 v
.add_decl
("/* allocate {mtype} */")
437 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
438 v
.add
("struct {mtype.c_name}*res = GC_MALLOC(sizeof(struct {mtype.c_name}));")
439 v
.add
("res->classid = {self.classid(mtype)};")
440 v
.add
("res->value = value;")
441 v
.add
("return (val*)res;")
446 # look for a needed .h and .c file for a given .nit source-file
447 # FIXME: bad API, parameter should be a MModule, not its source-file
448 fun add_extern
(file
: String)
450 file
= file
.strip_extension
(".nit")
451 var tryfile
= file
+ ".nit.h"
452 if tryfile
.file_exists
then
453 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
455 tryfile
= file
+ "_nit.h"
456 if tryfile
.file_exists
then
457 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
459 tryfile
= file
+ ".nit.c"
460 if tryfile
.file_exists
then
461 self.extern_bodies
.add
(tryfile
)
463 tryfile
= file
+ "_nit.c"
464 if tryfile
.file_exists
then
465 self.extern_bodies
.add
(tryfile
)
469 # Initialize a visitor specific for a compiler engine
470 fun new_visitor
: GlobalCompilerVisitor do return new GlobalCompilerVisitor(self)
472 # Generate the main C function.
474 # allocate the Sys object if it exists
475 # call init if is exists
476 # call main if it exists
477 fun compile_main_function
479 var v
= self.new_visitor
480 v
.add_decl
("int glob_argc;")
481 v
.add_decl
("char **glob_argv;")
482 v
.add_decl
("val *glob_sys;")
483 v
.add_decl
("int main(int argc, char** argv) \{")
484 v
.add
("glob_argc = argc; glob_argv = argv;")
485 var main_type
= mainmodule
.sys_type
486 if main_type
!= null then
487 var mainmodule
= v
.compiler
.mainmodule
488 var glob_sys
= v
.init_instance
(main_type
)
489 v
.add
("glob_sys = {glob_sys};")
490 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
491 if main_init
!= null then
492 v
.send
(main_init
, [glob_sys
])
494 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
495 if main_method
!= null then
496 v
.send
(main_method
, [glob_sys
])
504 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
508 # Mangle a string to be a unique valid C identifier
509 fun to_cmangle
: String
512 var underscore
= false
514 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
520 res
.append
('_'.ascii
.to_s
)
523 if c
>= '0' and c
<= '9' then
526 else if c
== '_' then
531 res
.append
(c
.ascii
.to_s
)
539 # Escape " \ ' and non printable characters for literal C strings or characters
540 fun escape_to_c
: String
546 else if c
== '\0' then
548 else if c
== '"' then
550 else if c == '\'' then
552 else if c == '\\
' then
554 else if c.ascii < 32 then
555 b.append("\\{c.ascii.to_base(8, false)}")
565 # Return the C type associated to a given Nit static type
571 # Return the name of the C structure associated to a Nit live type
572 # FIXME: move to GlobalCompiler so we can check that self is a live type
573 fun c_name: String is abstract
574 protected var c_name_cache: nullable String protected writable
577 redef class MClassType
580 var res = self.c_name_cache
581 if res != null then return res
582 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
583 self.c_name_cache = res
587 redef fun ctype: String
589 if mclass.name == "Int" then
591 else if mclass.name == "Bool" then
593 else if mclass.name == "Char" then
595 else if mclass.name == "Float" then
597 else if mclass.name == "NativeString" then
599 else if mclass.name == "NativeArray" then
600 #return "{self.arguments.first.ctype}*"
602 else if mclass.kind == extern_kind then
610 redef class MGenericType
613 var res = self.c_name_cache
614 if res != null then return res
616 for t in self.arguments do
619 self.c_name_cache = res
624 # A C function associated to a Nit method
625 # Because of customization, a given Nit method can be compiler more that once
626 abstract class AbstractRuntimeFunction
627 # The associated Nit method
628 var mmethoddef: MMethodDef
630 # The mangled c name of the runtime_function
631 # Subclasses should redefine `build_c_name` instead
634 var res = self.c_name_cache
635 if res != null then return res
636 res = self.build_c_name
637 self.c_name_cache = res
641 # Non cached version of `c_name`
642 protected fun build_c_name: String is abstract
644 private var c_name_cache: nullable String = null
646 # Implements a call of the runtime_function
647 # May inline the body or generate a C function call
648 fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
650 # Generate the code for the RuntimeFunction
651 # Warning: compile more than once compilation makes CC unhappy
652 fun compile_to_c(compiler: GlobalCompiler) is abstract
655 # A runtime function customized on a specific monomrph receiver type
656 private class CustomizedRuntimeFunction
657 super AbstractRuntimeFunction
659 # The considered reciever
660 # (usually is a live type but no strong guarantee)
663 init(mmethoddef: MMethodDef, recv: MClassType)
669 redef fun build_c_name: String
671 var res = self.c_name_cache
672 if res != null then return res
673 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
674 res = self.mmethoddef.c_name
676 res = "{mmethoddef.c_name}__{recv.c_name}"
678 self.c_name_cache = res
683 # used in the compiler worklist
685 if not o isa CustomizedRuntimeFunction then return false
686 if self.mmethoddef != o.mmethoddef then return false
687 if self.recv != o.recv then return false
692 # used in the compiler work-list
694 var res = self.mmethoddef.hash + self.recv.hash
700 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
701 return self.mmethoddef.to_s
703 return "{self.mmethoddef}@{self.recv}"
707 # compile the code customized for the reciever
708 redef fun compile_to_c(compiler)
711 var mmethoddef = self.mmethoddef
712 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
713 print("problem: why do we compile {self} for {recv}?")
717 var v = compiler.new_visitor
718 var selfvar = new RuntimeVariable("self", recv, recv)
719 if compiler.runtime_type_analysis.live_types.has(recv) then
720 selfvar.is_exact = true
722 var arguments = new Array[RuntimeVariable]
723 var frame = new Frame(v, mmethoddef, recv, arguments)
727 var comment = new Buffer
728 var ret = mmethoddef.msignature.return_mtype
730 ret = v.resolve_for(ret, selfvar)
731 sig.append("{ret.ctype} ")
732 else if mmethoddef.mproperty.is_new then
734 sig.append("{ret.ctype} ")
738 sig.append(self.c_name)
739 sig.append("({recv.ctype} {selfvar}")
740 comment.append("(self: {recv}")
741 arguments.add(selfvar)
742 for i in [0..mmethoddef.msignature.arity[ do
743 var mtype = mmethoddef.msignature.mparameters[i].mtype
744 if i == mmethoddef.msignature.vararg_rank then
745 mtype = v.get_class("Array").get_mtype([mtype])
747 mtype = v.resolve_for(mtype, selfvar)
748 comment.append(", {mtype}")
749 sig.append(", {mtype.ctype} p{i}")
750 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
751 arguments.add(argvar)
756 comment.append(": {ret}")
758 compiler.header.add_decl("{sig};")
760 v.add_decl("/* method {self} for {comment} */")
761 v.add_decl("{sig} \{")
762 #v.add("printf(\"method {self} for {comment}\\n\");")
764 frame.returnvar = v.new_var(ret)
766 frame.returnlabel = v.get_name("RET_LABEL")
768 mmethoddef.compile_inside_to_c(v, arguments)
770 v.add("{frame.returnlabel.as(not null)}:;")
772 v.add("return {frame.returnvar.as(not null)};")
777 redef fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
779 var ret = self.mmethoddef.msignature.return_mtype
780 if self.mmethoddef.mproperty.is_new then
784 ret = v.resolve_for(ret, arguments.first)
786 if self.mmethoddef.can_inline(v) then
787 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
788 frame.returnlabel = v.get_name("RET_LABEL")
790 frame.returnvar = v.new_var(ret)
792 var old_frame = v.frame
794 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
795 self.mmethoddef.compile_inside_to_c(v, arguments)
796 v.add("{frame.returnlabel.as(not null)}:(void)0;")
799 return frame.returnvar
801 v.adapt_signature(self.mmethoddef, arguments)
802 v.compiler.todo(self)
804 v.add("{self.c_name}({arguments.join(",")});")
807 var res = v.new_var(ret)
808 v.add("{res} = {self.c_name}({arguments.join(",")});")
814 # A runtime variable hold a runtime value in C.
815 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
817 # The tricky point is that a single C variable can be associated to more than one RuntimeVariable because the static knowledge of the type of an expression can vary in the C code.
818 class RuntimeVariable
819 # The name of the variable in the C code
822 # The static type of the variable (as declard in C)
825 # The current casted type of the variable (as known in Nit)
826 var mcasttype: MType writable
828 # If the variable exaclty a mcasttype?
829 # false (usual value) means that the variable is a mcasttype or a subtype.
830 var is_exact: Bool writable = false
832 init(name: String, mtype: MType, mcasttype: MType)
836 self.mcasttype = mcasttype
837 assert not mtype.need_anchor
838 assert not mcasttype.need_anchor
841 redef fun to_s do return name
846 if self.is_exact then
852 if self.mtype == self.mcasttype then
853 type_str = "{mtype}{exact_str}"
855 type_str = "{mtype}({mcasttype}{exact_str})"
857 return "<{name}:{type_str}>"
861 # A visitor on the AST of property definition that generate the C code.
862 # Because of inlining, a visitor can visit more than one property.
863 class GlobalCompilerVisitor
864 # The associated compiler
865 var compiler: GlobalCompiler
867 init(compiler: GlobalCompiler)
869 self.compiler = compiler
870 compiler.visitors.add(self)
873 # Alias for self.compiler.mainmodule.object_type
874 fun object_type: MClassType do return self.compiler.mainmodule.object_type
876 # Alias for self.compiler.mainmodule.bool_type
877 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
879 # Force to get the primitive class named `name' or abort
880 fun get_class
(name
: String): MClass
882 return self.compiler
.mainmodule
.get_primitive_class
(name
)
885 # Force to get the primitive property named `name' in the instance `recv' or abort
886 fun get_property
(name
: String, recv
: MType): MMethod
888 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
, self.compiler
.mainmodule
)
892 var frame
: nullable Frame writable
894 # Anchor a type to the main module and the current receiver
895 fun anchor
(mtype
: MType): MType
897 if not mtype
.need_anchor
then return mtype
898 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
899 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
902 # Add a line in the main part of the generated C
909 # (used for local or global declaration)
910 fun add_decl
(s
: String)
912 self.decl_lines
.add
(s
)
915 private var lines
: List[String] = new List[String]
916 private var decl_lines
: List[String] = new List[String]
918 # The current visited AST node
919 var current_node
: nullable ANode = null
921 # Compile an expression an return its result
922 # `mtype` is the expected return type, pass null if no specific type is expected.
923 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
925 var old
= self.current_node
926 self.current_node
= nexpr
927 var res
= nexpr
.expr
(self).as(not null)
928 if mtype
!= null then
929 mtype
= self.anchor
(mtype
)
930 res
= self.autobox
(res
, mtype
)
932 self.current_node
= old
936 # Unsafely cast a value to a new type
937 # ie the result share the same C variable but my have a different mcasttype
938 # NOTE: if the adaptation is useless then `value' is returned as it.
939 # ENSURE: return.name == value.name
940 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
942 mtype
= self.anchor
(mtype
)
943 var valmtype
= value
.mcasttype
944 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
948 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
949 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
952 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
957 # Box or unbox a value to another type iff a C type conversion is needed
958 # ENSURE: result.mtype.ctype == mtype.ctype
959 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
961 if value
.mtype
== mtype
then
963 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
965 else if value
.mtype
.ctype
== "val*" then
966 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
967 else if mtype
.ctype
== "val*" then
968 var valtype
= value
.mtype
.as(MClassType)
969 var res
= self.new_var
(mtype
)
970 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
971 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
972 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
975 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
978 # Bad things will appen!
979 var res
= self.new_var
(mtype
)
980 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
981 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
986 # Correctly assign a left and a right value
987 # Boxing and unboxing is performed if required
988 fun assign
(left
, right
: RuntimeVariable)
990 right
= self.autobox
(right
, left
.mtype
)
991 self.add
("{left} = {right};")
995 # Alias for `self.expr(nexpr, self.bool_type)'
996 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
998 return expr
(nexpr
, bool_type
)
1001 # Compile a statement (if any)
1002 fun stmt
(nexpr
: nullable AExpr)
1004 if nexpr
== null then return
1005 var old
= self.current_node
1006 self.current_node
= nexpr
1008 self.current_node
= old
1011 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1012 fun debug
(message
: String)
1014 var node
= self.current_node
1015 if node
== null then
1016 print
"?: {message}"
1020 self.add
("/* DEBUG: {message} */")
1023 # Return a new uninitialized local runtime_variable
1024 fun new_var
(mtype
: MType): RuntimeVariable
1026 mtype
= self.anchor
(mtype
)
1027 var name
= self.get_name
("var")
1028 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1029 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1033 # Return a new uninitialized named runtime_variable
1034 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
1036 mtype
= self.anchor
(mtype
)
1037 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1038 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1042 # Return a new local runtime_variable initialized with the C expression `cexpr'.
1043 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
1045 var res
= new_var
(mtype
)
1046 self.add
("{res} = {cexpr};")
1050 # Return the local runtime_variable associated to a Nit local variable
1051 fun variable
(variable
: Variable): RuntimeVariable
1053 if self.variables
.has_key
(variable
) then
1054 return self.variables
[variable
]
1056 var name
= self.get_name
("var_{variable.name}")
1057 var mtype
= variable
.declared_type
.as(not null)
1058 mtype
= self.anchor
(mtype
)
1059 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1060 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1061 self.variables
[variable
] = res
1066 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
1068 # Return an unique and stable identifier associated with an escapemark
1069 fun escapemark_name
(e
: nullable EscapeMark): String
1072 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
1074 if name
== null then name
= "label"
1075 name
= get_name
(name
)
1076 escapemark_names
[e
] = name
1080 private var escapemark_names
= new HashMap[EscapeMark, String]
1082 # Return a new name based on `s' and unique in the visitor
1083 fun get_name
(s
: String): String
1085 if not self.names
.has
(s
) then
1089 var i
= self.last
+ 1
1092 if not self.names
.has
(s2
) then
1101 private var last
: Int = 0
1103 private var names
: HashSet[String] = new HashSet[String]
1105 # Generate a return with the value `s'
1106 fun ret
(s
: RuntimeVariable)
1108 self.assign
(self.frame
.returnvar
.as(not null), s
)
1109 self.add
("goto {self.frame.returnlabel.as(not null)};")
1112 # The runtime types that are acceptable for a given receiver.
1113 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
1115 var mtype
= recv
.mcasttype
1116 if recv
.is_exact
then
1117 assert mtype
isa MClassType
1118 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
1122 var cache
= self.compiler
.collect_types_cache
1123 if cache
.has_key
(mtype
) then
1126 var types
= new Array[MClassType]
1127 var mainmodule
= self.compiler
.mainmodule
1128 for t
in self.compiler
.runtime_type_analysis
.live_types
do
1129 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
1132 cache
[mtype
] = types
1136 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
1138 if not mtype
.need_anchor
then return mtype
1139 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
1140 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
1144 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable])
1146 var elttype
= arguments
.first
.mtype
1147 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
1148 if pname
== "[]" then
1149 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1151 else if pname
== "[]=" then
1152 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1154 else if pname
== "copy_to" then
1155 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
1156 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
1161 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable])
1163 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
1166 # Add a check and an abort for a null reciever is needed
1167 fun check_recv_notnull
(recv
: RuntimeVariable)
1169 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
1171 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
1173 self.add
("if ({recv} == NULL) \{")
1174 self.add_abort
("Reciever is null")
1179 # Generate a polymorphic send for the method `m' and the arguments `args'
1180 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1182 var types
= self.collect_types
(args
.first
)
1184 var res
: nullable RuntimeVariable
1185 var ret
= m
.intro
.msignature
.return_mtype
1187 ret
= args
.first
.mtype
1188 res
= self.new_var
(ret
)
1189 else if ret
== null then
1192 ret
= self.resolve_for
(ret
, args
.first
)
1193 res
= self.new_var
(ret
)
1196 self.add
("/* send {m} on {args.first.inspect} */")
1197 if args
.first
.mtype
.ctype
!= "val*" then
1198 var mclasstype
= args
.first
.mtype
.as(MClassType)
1199 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
1200 self.add
("/* skip, no method {m} */")
1203 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, mclasstype
)
1204 if propdefs
.length
== 0 then
1205 self.add
("/* skip, no method {m} */")
1208 assert propdefs
.length
== 1
1209 var propdef
= propdefs
.first
1210 var res2
= self.call
(propdef
, mclasstype
, args
)
1211 if res
!= null then self.assign
(res
, res2
.as(not null))
1214 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
1215 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
1216 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
1217 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
1218 if m
.name
== "==" then
1220 if args
[1].mcasttype
isa MNullableType then
1221 self.add
("{res} = ({args[1]} == NULL);")
1222 else if args
[1].mcasttype
isa MNullType then
1223 self.add
("{res} = 1; /* is null */")
1225 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
1227 else if m
.name
== "!=" then
1229 if args
[1].mcasttype
isa MNullableType then
1230 self.add
("{res} = ({args[1]} != NULL);")
1231 else if args
[1].mcasttype
isa MNullType then
1232 self.add
("{res} = 0; /* is null */")
1234 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
1237 self.add_abort
("Reciever is null")
1241 if types
.is_empty
then
1243 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
1244 self.bugtype
(args
.first
)
1249 self.add
("switch({args.first}->classid) \{")
1250 var last
= types
.last
1251 var defaultpropdef
: nullable MMethodDef = null
1253 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
1254 if propdefs
.length
== 0 then
1255 self.add
("/* skip {t}, no method {m} */")
1258 if propdefs
.length
> 1 then
1259 self.debug
("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
1261 var propdef
= propdefs
.first
1262 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
1263 defaultpropdef
= propdef
1266 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
1267 self.add
("default: /* test {t} */")
1269 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
1271 var res2
= self.call
(propdef
, t
, args
)
1272 if res
!= null then self.assign
(res
, res2
.as(not null))
1275 if defaultpropdef
!= null then
1276 self.add
("default: /* default is Object */")
1277 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
1278 if res
!= null then self.assign
(res
, res2
.as(not null))
1279 else if self.compiler
.hardening
then
1280 self.add
("default: /* bug */")
1281 self.bugtype
(args
.first
)
1287 # Generate a monomorphic send for the method `m', the type `t' and the arguments `args'
1288 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1290 assert t
isa MClassType
1291 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
1292 if propdefs
.length
== 0 then
1295 if propdefs
.length
> 1 then
1296 self.debug
("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
1298 var propdef
= propdefs
.first
1299 return self.call
(propdef
, t
, args
)
1302 fun check_valid_reciever
(recvtype
: MClassType)
1304 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
1305 print
"{recvtype} is not a live type"
1309 # Generate a static call on a method definition
1310 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1312 check_valid_reciever
(recvtype
)
1313 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
1314 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
1315 recvtype
= m
.mclassdef
.bound_mtype
1317 var recv
= self.autobox
(args
.first
, recvtype
)
1318 recv
= self.autoadapt
(recv
, recvtype
)
1321 self.varargize
(m
.msignature
.as(not null), args
)
1322 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
1323 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); exit(1);")
1324 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
1329 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
1330 return rm
.call
(self, args
)
1333 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
1335 var recv
= args
.first
1336 for i
in [0..m
.msignature
.arity
[ do
1337 var t
= m
.msignature
.mparameters
[i
].mtype
1338 if i
== m
.msignature
.vararg_rank
then
1341 t
= self.resolve_for
(t
, recv
)
1342 args
[i
+1] = self.autobox
(args
[i
+1], t
)
1346 # Transform varargs, in raw arguments, into a single argument of type Array
1347 # Note: this method modify the given `args`
1348 # If there is no vararg, then `args` is not modified.
1349 fun varargize
(msignature
: MSignature, args
: Array[RuntimeVariable])
1351 var recv
= args
.first
1352 var vararg_rank
= msignature
.vararg_rank
1353 if vararg_rank
>= 0 then
1354 assert args
.length
>= msignature
.arity
+ 1 # because of self
1356 args
= new Array[RuntimeVariable]
1358 args
.add
(rawargs
.first
) # recv
1360 for i
in [0..vararg_rank
[ do
1361 args
.add
(rawargs
[i
+1])
1364 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-msignature
.arity
1365 var vararg
= new Array[RuntimeVariable]
1366 for i
in [vararg_rank
..vararg_lastrank
] do
1367 vararg
.add
(rawargs
[i
+1])
1369 # FIXME: its it to late to determine the vararg type, this should have been done during a previous analysis
1370 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
1371 elttype
= self.resolve_for
(elttype
, recv
)
1372 args
.add
(self.array_instance
(vararg
, elttype
))
1374 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
1375 args
.add
(rawargs
[i
+1])
1378 rawargs
.add_all
(args
)
1382 fun bugtype
(recv
: RuntimeVariable)
1384 if recv
.mtype
.ctype
!= "val*" then return
1385 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
1386 self.add
("exit(1);")
1389 # Generate a polymorphic attribute is_set test
1390 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1392 check_recv_notnull
(recv
)
1394 var types
= self.collect_types
(recv
)
1396 var res
= self.new_var
(bool_type
)
1398 if types
.is_empty
then
1399 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1403 self.add
("/* isset {a} on {recv.inspect} */")
1404 self.add
("switch({recv}->classid) \{")
1405 var last
= types
.last
1407 if not self.compiler
.hardening
and t
== last
then
1408 self.add
("default: /*{self.compiler.classid(t)}*/")
1410 self.add
("case {self.compiler.classid(t)}:")
1412 var recv2
= self.autoadapt
(recv
, t
)
1413 var ta
= a
.intro
.static_mtype
.as(not null)
1414 ta
= self.resolve_for
(ta
, recv2
)
1415 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1416 if not ta
isa MNullableType then
1417 if ta
.ctype
== "val*" then
1418 self.add
("{res} = ({attr} != NULL);")
1420 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
1425 if self.compiler
.hardening
then
1426 self.add
("default: /* Bug */")
1434 # Generate a polymorphic attribute read
1435 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1437 check_recv_notnull
(recv
)
1439 var types
= self.collect_types
(recv
)
1441 var ret
= a
.intro
.static_mtype
.as(not null)
1442 ret
= self.resolve_for
(ret
, recv
)
1443 var res
= self.new_var
(ret
)
1445 if types
.is_empty
then
1446 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1450 self.add
("/* read {a} on {recv.inspect} */")
1451 self.add
("switch({recv}->classid) \{")
1452 var last
= types
.last
1454 if not self.compiler
.hardening
and t
== last
then
1455 self.add
("default: /*{self.compiler.classid(t)}*/")
1457 self.add
("case {self.compiler.classid(t)}:")
1459 var recv2
= self.autoadapt
(recv
, t
)
1460 var ta
= a
.intro
.static_mtype
.as(not null)
1461 ta
= self.resolve_for
(ta
, recv2
)
1462 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1463 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
1464 if ta
.ctype
== "val*" then
1465 self.add
("if ({res2} == NULL) \{")
1466 self.add_abort
("Uninitialized attribute {a.name}")
1469 self.add
("/*NOTYET isset on primitive attributes*/")
1472 self.assign
(res
, res2
)
1475 if self.compiler
.hardening
then
1476 self.add
("default: /* Bug */")
1484 # Generate a polymorphic attribute write
1485 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1487 check_recv_notnull
(recv
)
1489 var types
= self.collect_types
(recv
)
1491 if types
.is_empty
then
1492 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1496 self.add
("/* write {a} on {recv.inspect} */")
1497 self.add
("switch({recv}->classid) \{")
1498 var last
= types
.last
1500 if not self.compiler
.hardening
and t
== last
then
1501 self.add
("default: /*{self.compiler.classid(t)}*/")
1503 self.add
("case {self.compiler.classid(t)}:")
1505 var recv2
= self.autoadapt
(recv
, t
)
1506 var ta
= a
.intro
.static_mtype
.as(not null)
1507 ta
= self.resolve_for
(ta
, recv2
)
1508 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1511 if self.compiler
.hardening
then
1512 self.add
("default: /* Bug*/")
1518 # Generate a alloc-instance + init-attributes
1519 fun init_instance
(mtype
: MClassType): RuntimeVariable
1521 mtype
= self.anchor
(mtype
).as(MClassType)
1522 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1523 debug
"problem: {mtype} was detected dead"
1525 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1530 # Generate a polymorphic subtype test
1531 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1533 mtype
= self.anchor
(mtype
)
1534 var mclasstype
= mtype
1535 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
1536 assert mclasstype
isa MClassType
1537 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
1538 debug
"problem: {mtype} was detected cast-dead"
1542 var types
= self.collect_types
(value
)
1544 var res
= self.new_var
(bool_type
)
1546 self.add
("/* isa {mtype} on {value.inspect} */")
1547 if value
.mtype
.ctype
!= "val*" then
1548 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1549 self.add
("{res} = 1;")
1551 self.add
("{res} = 0;")
1555 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
1556 self.add
("if ({value} == NULL) \{")
1557 if mtype
isa MNullableType then
1558 self.add
("{res} = 1; /* isa {mtype} */")
1560 self.add
("{res} = 0; /* not isa {mtype} */")
1562 self.add
("\} else ")
1564 self.add
("switch({value}->classid) \{")
1566 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1567 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1570 self.add
("{res} = 1;")
1572 self.add
("default:")
1573 self.add
("{res} = 0;")
1579 # Generate the code required to dynamically check if 2 objects share the same runtime type
1580 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1582 var res
= self.new_var
(bool_type
)
1583 if value2
.mtype
.ctype
== "val*" then
1584 if value1
.mtype
.ctype
== "val*" then
1585 self.add
"{res} = {value1}->classid == {value2}->classid;"
1587 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
1590 if value1
.mtype
.ctype
== "val*" then
1591 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
1592 else if value1
.mcasttype
== value2
.mcasttype
then
1593 self.add
"{res} = 1;"
1595 self.add
"{res} = 0;"
1601 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1602 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
1603 fun class_name_string
(value
: RuntimeVariable): String
1605 var res
= self.get_name
("var_class_name")
1606 self.add_decl
("const char* {res};")
1607 if value
.mtype
.ctype
== "val*" then
1608 self.add
"{res} = class_names[{value}->classid];"
1610 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
1615 # Generate a Nit "is" for two runtime_variables
1616 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1618 var res
= self.new_var
(bool_type
)
1619 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1624 if value1
.mtype
.ctype
!= "val*" then
1625 if value2
.mtype
== value1
.mtype
then
1626 self.add
("{res} = {value1} == {value2};")
1627 else if value2
.mtype
.ctype
!= "val*" then
1628 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1630 var mtype1
= value1
.mtype
.as(MClassType)
1631 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1632 self.add
("if ({res}) \{")
1633 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1637 var s
= new Array[String]
1638 for t
in self.compiler
.live_primitive_types
do
1639 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1640 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1641 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1644 self.add
("{res} = {value1} == {value2};")
1646 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1652 # Generate a check-init-instance
1653 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType)
1655 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1657 mtype
= self.anchor
(mtype
).as(MClassType)
1658 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1659 debug
"problem: {mtype} was detected dead"
1662 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
1665 # Generate an integer value
1666 fun int_instance
(value
: Int): RuntimeVariable
1668 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1669 self.add
("{res} = {value};")
1673 # Generate an array value
1674 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1676 elttype
= self.anchor
(elttype
)
1677 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
1678 var res
= self.init_instance
(arraytype
)
1679 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1680 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1682 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1683 for i
in [0..array
.length
[ do
1684 var r
= self.autobox
(array
[i
], elttype
)
1685 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1687 var length
= self.int_instance
(array
.length
)
1688 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1689 self.check_init_instance
(res
, arraytype
)
1694 # Generate a string value
1695 fun string_instance
(string
: String): RuntimeVariable
1697 var mtype
= self.get_class
("String").mclass_type
1698 var name
= self.get_name
("varonce")
1699 self.add_decl
("static {mtype.ctype} {name};")
1700 var res
= self.new_var
(mtype
)
1701 self.add
("if ({name}) \{")
1702 self.add
("{res} = {name};")
1703 self.add
("\} else \{")
1704 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1705 self.add
("{nat} = \"{string.escape_to_c}\
";")
1706 var res2
= self.init_instance
(mtype
)
1707 self.add
("{res} = {res2};")
1708 var length
= self.int_instance
(string
.length
)
1709 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
1710 self.check_init_instance
(res
, mtype
)
1711 self.add
("{name} = {res};")
1716 # Generate generic abort
1717 # used by aborts, asserts, casts, etc.
1718 fun add_abort
(message
: String)
1720 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1721 self.add
("fprintf(stderr, \"Runtime error
: %s
(%s
:%d
)\\n\
", \"{message.escape_to_c}\
", \"{self.current_node.location.file.filename.escape_to_c}\
", {current_node.location.line_start});")
1723 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
1725 self.add
("exit(1);")
1729 # A frame correspond to a visited property in a GlobalCompilerVisitor
1731 # The associated visitor
1733 var visitor
: GlobalCompilerVisitor
1735 # The executed property.
1736 # A Method in case of a call, an attribute in case of a default initialization.
1737 var mpropdef
: MPropDef
1739 # The static type of the receiver
1740 var receiver
: MClassType
1742 # Arguments of the method (the first is the receiver)
1743 var arguments
: Array[RuntimeVariable]
1745 # The runtime_variable associated to the return (in a function)
1746 var returnvar
: nullable RuntimeVariable writable = null
1748 # The label at the end of the property
1749 var returnlabel
: nullable String writable = null
1752 redef class MPropDef
1753 private var c_name_cache
: nullable String
1755 # The mangled name associated to the property
1758 var res
= self.c_name_cache
1759 if res
!= null then return res
1760 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1761 self.c_name_cache
= res
1766 redef class MMethodDef
1767 # Can the body be inlined?
1768 fun can_inline
(v
: GlobalCompilerVisitor): Bool
1770 var modelbuilder
= v
.compiler
.modelbuilder
1771 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1772 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1773 return npropdef
.can_inline
1774 else if self.mproperty
.name
== "init" then
1775 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1782 # Inline the body in another visitor
1783 fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1785 var modelbuilder
= v
.compiler
.modelbuilder
1786 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1787 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1788 var oldnode
= v
.current_node
1789 v
.current_node
= npropdef
1790 self.compile_parameter_check
(v
, arguments
)
1791 npropdef
.compile_to_c
(v
, self, arguments
)
1792 v
.current_node
= oldnode
1793 else if self.mproperty
.name
== "init" then
1794 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1795 var oldnode
= v
.current_node
1796 v
.current_node
= nclassdef
1797 self.compile_parameter_check
(v
, arguments
)
1798 nclassdef
.compile_to_c
(v
, self, arguments
)
1799 v
.current_node
= oldnode
1806 # Generate type checks in the C code to check covariant parameters
1807 fun compile_parameter_check
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable])
1809 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_covariance
.value
then return
1811 for i
in [0..msignature
.arity
[ do
1812 # skip test for vararg since the array is instantiated with the correct polymorphic type
1813 if msignature
.vararg_rank
== i
then continue
1815 # skip if the cast is not required
1816 var origmtype
= self.mproperty
.intro
.msignature
.mparameters
[i
].mtype
1817 if not origmtype
.need_anchor
then continue
1819 # get the parameter type
1820 var mtype
= self.msignature
.mparameters
[i
].mtype
1823 # note that v decides if and how to implements the cast
1824 v
.add
("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1825 var cond
= v
.type_test
( arguments
[i
+1], mtype
)
1826 v
.add
("if (!{cond}) \{")
1827 #var x = v.class_name_string(arguments[i+1])
1828 #var y = v.class_name_string(arguments.first)
1829 #v.add("fprintf(stderr, \"expected {mtype} (self is %s), got %s for {arguments[i+1].inspect}\\n\", {y}, {x});")
1830 v
.add_abort
("Cast failed")
1836 redef class APropdef
1837 fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1839 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
1840 debug
("Not yet implemented")
1843 fun can_inline
: Bool do return true
1846 redef class AConcreteMethPropdef
1847 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1849 for i
in [0..mpropdef
.msignature
.arity
[ do
1850 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1851 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1853 # Call the implicit super-init
1854 var auto_super_inits
= self.auto_super_inits
1855 if auto_super_inits
!= null then
1856 var selfarg
= [arguments
.first
]
1857 for auto_super_init
in auto_super_inits
do
1858 if auto_super_init
.intro
.msignature
.arity
== 0 then
1859 v
.send
(auto_super_init
, selfarg
)
1861 v
.send
(auto_super_init
, arguments
)
1865 v
.stmt
(self.n_block
)
1868 redef fun can_inline
1870 if self.auto_super_inits
!= null then return false
1871 var nblock
= self.n_block
1872 if nblock
== null then return true
1873 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
1874 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
1879 redef class AInternMethPropdef
1880 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1882 var pname
= mpropdef
.mproperty
.name
1883 var cname
= mpropdef
.mclassdef
.mclass
.name
1884 var ret
= mpropdef
.msignature
.return_mtype
1886 ret
= v
.resolve_for
(ret
, arguments
.first
)
1888 if pname
!= "==" and pname
!= "!=" then
1889 v
.adapt_signature
(mpropdef
, arguments
)
1891 if cname
== "Int" then
1892 if pname
== "output" then
1893 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1895 else if pname
== "object_id" then
1896 v
.ret
(arguments
.first
)
1898 else if pname
== "+" then
1899 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1901 else if pname
== "-" then
1902 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1904 else if pname
== "unary -" then
1905 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1907 else if pname
== "succ" then
1908 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1910 else if pname
== "prec" then
1911 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1913 else if pname
== "*" then
1914 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1916 else if pname
== "/" then
1917 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1919 else if pname
== "%" then
1920 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1922 else if pname
== "lshift" then
1923 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1925 else if pname
== "rshift" then
1926 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1928 else if pname
== "==" then
1929 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1931 else if pname
== "!=" then
1932 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1933 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1935 else if pname
== "<" then
1936 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1938 else if pname
== ">" then
1939 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1941 else if pname
== "<=" then
1942 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1944 else if pname
== ">=" then
1945 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1947 else if pname
== "to_f" then
1948 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1950 else if pname
== "ascii" then
1951 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1954 else if cname
== "Char" then
1955 if pname
== "output" then
1956 v
.add
("printf(\"%c\
", {arguments.first});")
1958 else if pname
== "object_id" then
1959 v
.ret
(arguments
.first
)
1961 else if pname
== "+" then
1962 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1964 else if pname
== "-" then
1965 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1967 else if pname
== "==" then
1968 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1970 else if pname
== "!=" then
1971 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1972 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1974 else if pname
== "succ" then
1975 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1977 else if pname
== "prec" then
1978 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1980 else if pname
== "<" then
1981 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1983 else if pname
== ">" then
1984 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1986 else if pname
== "<=" then
1987 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1989 else if pname
== ">=" then
1990 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1992 else if pname
== "to_i" then
1993 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
1995 else if pname
== "ascii" then
1996 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
1999 else if cname
== "Bool" then
2000 if pname
== "output" then
2001 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
2003 else if pname
== "object_id" then
2004 v
.ret
(arguments
.first
)
2006 else if pname
== "==" then
2007 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2009 else if pname
== "!=" then
2010 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2011 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2014 else if cname
== "Float" then
2015 if pname
== "output" then
2016 v
.add
("printf(\"%f\\n\
", {arguments.first});")
2018 else if pname
== "object_id" then
2019 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
2021 else if pname
== "+" then
2022 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2024 else if pname
== "-" then
2025 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2027 else if pname
== "unary -" then
2028 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2030 else if pname
== "succ" then
2031 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2033 else if pname
== "prec" then
2034 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
2036 else if pname
== "*" then
2037 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2039 else if pname
== "/" then
2040 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2042 else if pname
== "==" then
2043 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2045 else if pname
== "!=" then
2046 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2047 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2049 else if pname
== "<" then
2050 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2052 else if pname
== ">" then
2053 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2055 else if pname
== "<=" then
2056 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2058 else if pname
== ">=" then
2059 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2061 else if pname
== "to_i" then
2062 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2065 else if cname
== "Char" then
2066 if pname
== "output" then
2067 v
.add
("printf(\"%c\
", {arguments.first});")
2069 else if pname
== "object_id" then
2070 v
.ret
(arguments
.first
)
2072 else if pname
== "==" then
2073 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2075 else if pname
== "!=" then
2076 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2077 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2079 else if pname
== "ascii" then
2080 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
2083 else if cname
== "NativeString" then
2084 if pname
== "[]" then
2085 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
2087 else if pname
== "[]=" then
2088 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2090 else if pname
== "copy_to" then
2091 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2093 else if pname
== "atoi" then
2094 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
2097 else if cname
== "NativeArray" then
2098 v
.native_array_def
(pname
, ret
, arguments
)
2101 if pname
== "exit" then
2102 v
.add
("exit({arguments[1]});")
2104 else if pname
== "sys" then
2105 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
2107 else if pname
== "calloc_string" then
2108 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
2110 else if pname
== "calloc_array" then
2111 v
.calloc_array
(ret
.as(not null), arguments
)
2113 else if pname
== "object_id" then
2114 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2116 else if pname
== "is_same_type" then
2117 v
.ret
(v
.is_same_type_test
(arguments
[0], arguments
[1]))
2119 else if pname
== "output_class_name" then
2120 var nat
= v
.class_name_string
(arguments
.first
)
2121 v
.add
("printf(\"%s\\n\
", {nat});")
2123 else if pname
== "native_class_name" then
2124 var nat
= v
.class_name_string
(arguments
.first
)
2125 v
.ret
(v
.new_expr
("(char*){nat}", ret
.as(not null)))
2127 else if pname
== "force_garbage_collection" then
2128 v
.add
("GC_gcollect();")
2131 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at
{location.to_s}\\n\
");")
2132 debug
("Not implemented {mpropdef}")
2136 redef class AExternMethPropdef
2137 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2140 var nextern
= self.n_extern
2141 if nextern
== null then
2142 v
.add
("fprintf(stderr, \"NOT YET IMPLEMENTED nitni
for {mpropdef} at
{location.to_s}\\n\
");")
2146 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2147 if location
.file
!= null then
2148 var file
= location
.file
.filename
2149 v
.compiler
.add_extern
(file
)
2151 var res
: nullable RuntimeVariable = null
2152 var ret
= mpropdef
.msignature
.return_mtype
2154 ret
= v
.resolve_for
(ret
, arguments
.first
)
2155 res
= v
.new_var
(ret
)
2157 v
.adapt_signature
(mpropdef
, arguments
)
2160 v
.add
("{externname}({arguments.join(", ")});")
2162 v
.add
("{res} = {externname}({arguments.join(", ")});")
2168 redef class AExternInitPropdef
2169 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2172 var nextern
= self.n_extern
2173 if nextern
== null then
2174 debug
("{mpropdef} need extern name")
2177 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2178 if location
.file
!= null then
2179 var file
= location
.file
.filename
2180 v
.compiler
.add_extern
(file
)
2182 v
.adapt_signature
(mpropdef
, arguments
)
2183 var ret
= arguments
.first
.mtype
2184 var res
= v
.new_var
(ret
)
2188 v
.add
("{res} = {externname}({arguments.join(", ")});")
2193 redef class AAttrPropdef
2194 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2196 if arguments
.length
== 1 then
2197 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
2198 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
2200 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
2204 fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2206 var nexpr
= self.n_expr
2207 if nexpr
!= null then
2208 var oldnode
= v
.current_node
2209 v
.current_node
= self
2210 var old_frame
= v
.frame
2211 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2213 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
2214 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
2216 v
.current_node
= oldnode
2220 fun check_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2222 var nexpr
= self.n_expr
2223 if nexpr
!= null then return
2225 var oldnode
= v
.current_node
2226 v
.current_node
= self
2227 var old_frame
= v
.frame
2228 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2230 # Force read to check the initialization
2231 v
.read_attribute
(self.mpropdef
.mproperty
, recv
)
2233 v
.current_node
= oldnode
2237 redef class AClassdef
2238 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
2240 if mpropdef
== self.mfree_init
then
2241 var super_inits
= self.super_inits
2242 if super_inits
!= null then
2243 assert arguments
.length
== 1
2244 for su
in super_inits
do
2245 v
.send
(su
, arguments
)
2249 var recv
= arguments
.first
2251 # Collect undefined attributes
2252 for npropdef
in self.n_propdefs
do
2253 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
2254 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
2264 redef class ADeferredMethPropdef
2265 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2267 v
.add_abort
("Deferred method called")
2270 redef fun can_inline
do return true
2274 # Try to compile self as an expression
2275 # Do not call this method directly, use `v.expr' instead
2276 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
2278 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
2279 var mtype
= self.mtype
2280 if mtype
== null then
2283 var res
= v
.new_var
(mtype
)
2284 v
.add
("/* {res} = NOT YET {class_name} */")
2289 # Try to compile self as a statement
2290 # Do not call this method directly, use `v.stmt' instead
2291 private fun stmt
(v
: GlobalCompilerVisitor)
2294 if res
!= null then v
.add
("{res};")
2299 redef class ABlockExpr
2302 for e
in self.n_expr
do
2308 redef class AVardeclExpr
2311 var variable
= self.variable
.as(not null)
2312 var ne
= self.n_expr
2314 var i
= v
.expr
(ne
, variable
.declared_type
)
2315 v
.assign
(v
.variable
(variable
), i
)
2320 redef class AVarExpr
2323 var res
= v
.variable
(self.variable
.as(not null))
2324 var mtype
= self.mtype
.as(not null)
2325 return v
.autoadapt
(res
, mtype
)
2329 redef class AVarAssignExpr
2332 var variable
= self.variable
.as(not null)
2333 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
2334 v
.assign
(v
.variable
(variable
), i
)
2338 redef class AVarReassignExpr
2341 var variable
= self.variable
.as(not null)
2342 var vari
= v
.variable
(variable
)
2343 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
2344 var res
= v
.send
(reassign_property
.mproperty
, [vari
, value
])
2346 v
.assign
(v
.variable
(variable
), res
)
2350 redef class ASelfExpr
2353 return v
.frame
.arguments
.first
2357 redef class AContinueExpr
2360 v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
2364 redef class ABreakExpr
2367 v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
2371 redef class AReturnExpr
2374 var nexpr
= self.n_expr
2375 if nexpr
!= null then
2376 var returnvar
= v
.frame
.returnvar
.as(not null)
2377 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
2378 v
.assign
(returnvar
, i
)
2380 v
.add
("goto {v.frame.returnlabel.as(not null)};")
2384 redef class AAbortExpr
2387 v
.add_abort
("Aborted")
2394 var cond
= v
.expr_bool
(self.n_expr
)
2395 v
.add
("if ({cond})\{")
2403 redef class AIfexprExpr
2406 var res
= v
.new_var
(self.mtype
.as(not null))
2407 var cond
= v
.expr_bool
(self.n_expr
)
2408 v
.add
("if ({cond})\{")
2409 v
.assign
(res
, v
.expr
(self.n_then
, null))
2411 v
.assign
(res
, v
.expr
(self.n_else
, null))
2420 v
.stmt
(self.n_block
)
2421 var escapemark
= self.escapemark
2422 if escapemark
!= null then
2423 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2428 redef class AWhileExpr
2432 var cond
= v
.expr_bool
(self.n_expr
)
2433 v
.add
("if (!{cond}) break;")
2434 v
.stmt
(self.n_block
)
2435 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2437 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2441 redef class ALoopExpr
2445 v
.stmt
(self.n_block
)
2446 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2448 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2452 redef class AForExpr
2455 var cl
= v
.expr
(self.n_expr
, null)
2456 var it_meth
= self.method_iterator
2457 assert it_meth
!= null
2458 var it
= v
.send
(it_meth
, [cl
])
2461 var isok_meth
= self.method_is_ok
2462 assert isok_meth
!= null
2463 var ok
= v
.send
(isok_meth
, [it
])
2465 v
.add
("if(!{ok}) break;")
2466 if self.variables
.length
== 1 then
2467 var item_meth
= self.method_item
2468 assert item_meth
!= null
2469 var i
= v
.send
(item_meth
, [it
])
2471 v
.assign
(v
.variable
(variables
.first
), i
)
2472 else if self.variables
.length
== 2 then
2473 var key_meth
= self.method_key
2474 assert key_meth
!= null
2475 var i
= v
.send
(key_meth
, [it
])
2477 v
.assign
(v
.variable
(variables
[0]), i
)
2478 var item_meth
= self.method_item
2479 assert item_meth
!= null
2480 i
= v
.send
(item_meth
, [it
])
2482 v
.assign
(v
.variable
(variables
[1]), i
)
2486 v
.stmt
(self.n_block
)
2487 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2488 var next_meth
= self.method_next
2489 assert next_meth
!= null
2490 v
.send
(next_meth
, [it
])
2492 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2496 redef class AAssertExpr
2499 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
2501 var cond
= v
.expr_bool
(self.n_expr
)
2502 v
.add
("if (!{cond}) \{")
2506 v
.add_abort
("Assert '{nid.text}' failed")
2508 v
.add_abort
("Assert failed")
2517 var res
= v
.new_var
(self.mtype
.as(not null))
2518 var i1
= v
.expr_bool
(self.n_expr
)
2519 v
.add
("if ({i1}) \{")
2522 var i2
= v
.expr_bool
(self.n_expr2
)
2523 v
.add
("{res} = {i2};")
2529 redef class AAndExpr
2532 var res
= v
.new_var
(self.mtype
.as(not null))
2533 var i1
= v
.expr_bool
(self.n_expr
)
2534 v
.add
("if (!{i1}) \{")
2537 var i2
= v
.expr_bool
(self.n_expr2
)
2538 v
.add
("{res} = {i2};")
2544 redef class ANotExpr
2547 var cond
= v
.expr_bool
(self.n_expr
)
2548 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2552 redef class AOrElseExpr
2555 var res
= v
.new_var
(self.mtype
.as(not null))
2556 var i1
= v
.expr
(self.n_expr
, null)
2557 v
.add
("if ({i1}!=NULL) \{")
2560 var i2
= v
.expr
(self.n_expr2
, null)
2570 var value1
= v
.expr
(self.n_expr
, null)
2571 var value2
= v
.expr
(self.n_expr2
, null)
2572 return v
.equal_test
(value1
, value2
)
2576 redef class AIntExpr
2579 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2583 redef class AFloatExpr
2586 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2590 redef class ACharExpr
2593 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2597 redef class AArrayExpr
2600 var mtype
= self.mtype
.as(MClassType).arguments
.first
2601 var array
= new Array[RuntimeVariable]
2602 for nexpr
in self.n_exprs
.n_exprs
do
2603 var i
= v
.expr
(nexpr
, mtype
)
2606 return v
.array_instance
(array
, mtype
)
2610 redef class AStringFormExpr
2613 return v
.string_instance
(self.value
.as(not null))
2617 redef class ASuperstringExpr
2620 var array
= new Array[RuntimeVariable]
2621 for ne
in self.n_exprs
do
2622 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2623 var i
= v
.expr
(ne
, null)
2626 var a
= v
.array_instance
(array
, v
.object_type
)
2627 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2632 redef class ACrangeExpr
2635 var i1
= v
.expr
(self.n_expr
, null)
2636 var i2
= v
.expr
(self.n_expr2
, null)
2637 var mtype
= self.mtype
.as(MClassType)
2638 var res
= v
.init_instance
(mtype
)
2639 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2640 v
.check_init_instance
(res
, mtype
)
2645 redef class AOrangeExpr
2648 var i1
= v
.expr
(self.n_expr
, null)
2649 var i2
= v
.expr
(self.n_expr2
, null)
2650 var mtype
= self.mtype
.as(MClassType)
2651 var res
= v
.init_instance
(mtype
)
2652 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2653 v
.check_init_instance
(res
, mtype
)
2658 redef class ATrueExpr
2661 return v
.new_expr
("1", self.mtype
.as(not null))
2665 redef class AFalseExpr
2668 return v
.new_expr
("0", self.mtype
.as(not null))
2672 redef class ANullExpr
2675 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2680 redef class AIsaExpr
2683 var i
= v
.expr
(self.n_expr
, null)
2684 return v
.type_test
(i
, self.cast_type
.as(not null))
2688 redef class AAsCastExpr
2691 var i
= v
.expr
(self.n_expr
, null)
2692 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2694 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2695 v
.add
("if (!{cond}) \{")
2696 v
.add_abort
("Cast failed")
2702 redef class AAsNotnullExpr
2705 var i
= v
.expr
(self.n_expr
, null)
2706 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2708 v
.add
("if ({i} == NULL) \{")
2709 v
.add_abort
("Cast failed")
2715 redef class AParExpr
2718 return v
.expr
(self.n_expr
, null)
2722 redef class AOnceExpr
2725 var mtype
= self.mtype
.as(not null)
2726 var name
= v
.get_name
("varonce")
2727 var guard
= v
.get_name
(name
+ "_guard")
2728 v
.add_decl
("static {mtype.ctype} {name};")
2729 v
.add_decl
("static int {guard};")
2730 var res
= v
.new_var
(mtype
)
2731 v
.add
("if ({guard}) \{")
2732 v
.add
("{res} = {name};")
2734 var i
= v
.expr
(self.n_expr
, mtype
)
2735 v
.add
("{res} = {i};")
2736 v
.add
("{name} = {res};")
2737 v
.add
("{guard} = 1;")
2743 redef class ASendExpr
2746 var recv
= v
.expr
(self.n_expr
, null)
2748 for a
in self.raw_arguments
.as(not null) do
2749 args
.add
(v
.expr
(a
, null))
2751 var mproperty
= self.mproperty
.as(not null)
2752 return v
.send
(mproperty
, args
)
2756 redef class ASendReassignFormExpr
2759 var recv
= v
.expr
(self.n_expr
, null)
2761 for a
in self.raw_arguments
.as(not null) do
2762 args
.add
(v
.expr
(a
, null))
2764 var value
= v
.expr
(self.n_value
, null)
2766 var mproperty
= self.mproperty
.as(not null)
2767 var left
= v
.send
(mproperty
, args
)
2770 var res
= v
.send
(reassign_property
.mproperty
, [left
, value
])
2774 v
.send
(self.write_mproperty
.as(not null), args
)
2778 redef class ASuperExpr
2781 var recv
= v
.frame
.arguments
.first
2783 for a
in self.n_args
.n_exprs
do
2784 args
.add
(v
.expr
(a
, null))
2786 if args
.length
== 1 then
2787 args
= v
.frame
.arguments
2790 var mproperty
= self.mproperty
2791 if mproperty
!= null then
2792 if mproperty
.intro
.msignature
.arity
== 0 then
2796 var res
= v
.send
(mproperty
, args
)
2800 # stantard call-next-method
2801 var mpropdef
= v
.frame
.mpropdef
2802 # FIXME: we do not want an ugly static call!
2803 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2804 if mpropdefs
.length
!= 1 then
2805 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
2806 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2808 mpropdef
= mpropdefs
.first
2809 assert mpropdef
isa MMethodDef
2810 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2815 redef class ANewExpr
2818 var mproperty
= self.mproperty
.as(not null)
2819 var mtype
= self.mtype
.as(MClassType)
2821 var ctype
= mtype
.ctype
2822 if ctype
== "val*" then
2823 recv
= v
.init_instance
(mtype
)
2824 else if ctype
== "void*" then
2825 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2827 debug
("cannot new {mtype}")
2831 for a
in self.n_args
.n_exprs
do
2832 args
.add
(v
.expr
(a
, null))
2834 var res2
= v
.send
(mproperty
, args
)
2835 if res2
!= null then
2836 #self.debug("got {res2} from {mproperty}. drop {recv}")
2839 v
.check_init_instance
(recv
, mtype
)
2844 redef class AAttrExpr
2847 var recv
= v
.expr
(self.n_expr
, null)
2848 var mproperty
= self.mproperty
.as(not null)
2849 return v
.read_attribute
(mproperty
, recv
)
2853 redef class AAttrAssignExpr
2856 var recv
= v
.expr
(self.n_expr
, null)
2857 var i
= v
.expr
(self.n_value
, null)
2858 var mproperty
= self.mproperty
.as(not null)
2859 v
.write_attribute
(mproperty
, recv
, i
)
2863 redef class AAttrReassignExpr
2866 var recv
= v
.expr
(self.n_expr
, null)
2867 var value
= v
.expr
(self.n_value
, null)
2868 var mproperty
= self.mproperty
.as(not null)
2869 var attr
= v
.read_attribute
(mproperty
, recv
)
2870 var res
= v
.send
(reassign_property
.mproperty
, [attr
, value
])
2872 v
.write_attribute
(mproperty
, recv
, res
)
2876 redef class AIssetAttrExpr
2879 var recv
= v
.expr
(self.n_expr
, null)
2880 var mproperty
= self.mproperty
.as(not null)
2881 return v
.isset_attribute
(mproperty
, recv
)
2885 redef class ADebugTypeExpr