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_autocast
: OptionBool = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
54 var opt_no_check_other
: OptionBool = new OptionBool("Disable implicit tests: unset attribute, null receiver (dangerous)", "--no-check-other")
59 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_hardening
)
60 self.option_context
.add_option
(self.opt_no_check_covariance
, self.opt_no_check_initialization
, self.opt_no_check_assert
, self.opt_no_check_autocast
, self.opt_no_check_other
)
64 redef class ModelBuilder
65 # Entry point to performs a global compilation on the AST of a complete program.
66 # `mainmodule` is the main module of the program
67 # `runtime_type_analysis` is a already computer type analysis.
68 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
71 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
73 var compiler
= new GlobalCompiler(mainmodule
, runtime_type_analysis
, self)
74 var v
= compiler
.new_visitor
76 v
.add_decl
("#include <stdlib.h>")
77 v
.add_decl
("#include <stdio.h>")
78 v
.add_decl
("#include <string.h>")
80 # TODO: Better way to activate the GC
81 v
.add_decl
("#include <gc/gc.h>")
82 #v.add_decl("#define GC_MALLOC(x) calloc(1, (x))")
84 # Declaration of structures the live Nit types
85 # Each live type is generated as an independent C `struct' type.
86 # They only share a common first field `classid` used to implement the polymorphism.
87 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val' that contains only the `classid` field.
89 v
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
90 for t
in runtime_type_analysis
.live_types
do
91 compiler
.declare_runtimeclass
(v
, t
)
94 # Global variable used by the legacy native interface
96 v
.add_decl
("extern int glob_argc;")
97 v
.add_decl
("extern char **glob_argv;")
98 v
.add_decl
("extern val *glob_sys;")
100 # Class names (for the class_name and output_class_name methods)
102 v
.add_decl
("extern const char const * class_names[];")
103 v
.add
("const char const * class_names[] = \{")
104 for t
in runtime_type_analysis
.live_types
do
105 v
.add
("\"{t}\
", /* {compiler.classid(t)} */")
110 # Init instance code (allocate and init-arguments)
112 for t
in runtime_type_analysis
.live_types
do
113 if t
.ctype
== "val*" then
114 compiler
.generate_init_instance
(t
)
115 compiler
.generate_check_init_instance
(t
)
117 compiler
.generate_box_instance
(t
)
121 # The main function of the C
122 compiler
.compile_main_function
124 # Compile until all runtime_functions are visited
126 while not compiler
.todos
.is_empty
do
127 var m
= compiler
.todos
.shift
128 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
129 m
.compile_to_c
(compiler
)
131 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
134 self.toolcontext
.info
("*** END VISITING: {time1-time0} ***", 2)
135 write_and_make
(compiler
)
138 protected fun write_and_make
(compiler
: GlobalCompiler)
140 var mainmodule
= compiler
.mainmodule
142 # Generate the .h and .c files
143 # A single C file regroups many compiled rumtime functions
144 # 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
147 var outname
= self.toolcontext
.opt_output
.value
148 if outname
== null then
149 outname
= "{mainmodule.name}.bin"
152 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
153 var h
= new OFStream.open
(hfilename
)
154 for l
in compiler
.header
.decl_lines
do
160 var cfiles
= new Array[String]
162 var file
: nullable OFStream = null
167 for vis
in compiler
.visitors
do
168 count
+= vis
.lines
.length
169 if file
== null or count
> 10000 then
171 if file
!= null then file
.close
172 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
173 cfiles
.add
(cfilename
)
174 file
= new OFStream.open
(cfilename
)
175 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
176 count
= vis
.lines
.length
178 if vis
!= compiler
.header
then
179 for l
in vis
.decl_lines
do
184 for l
in vis
.lines
do
189 if file
!= null then file
.close
191 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
193 # Generate the Makefile
195 var makename
= ".nit_compile/{mainmodule.name}.mk"
196 var makefile
= new OFStream.open
(makename
)
198 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
199 makefile
.write
("all: {outname}\n\n")
201 var ofiles
= new Array[String]
202 # Compile each generated file
204 var o
= f
.strip_extension
(".c") + ".o"
205 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
208 # Compile each required extern body into a specific .o
209 for f
in compiler
.extern_bodies
do
211 var o
= ".nit_compile/{mainmodule.name}.{i}.o"
212 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
216 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
218 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
220 self.toolcontext
.info
("Generated makefile: {makename}", 2)
223 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
225 # Execute the Makefile
227 if self.toolcontext
.opt_no_cc
.value
then return
230 self.toolcontext
.info
("*** COMPILING C ***", 1)
231 self.toolcontext
.info
("make -B -f {makename} -j 4", 2)
234 if self.toolcontext
.verbose_level
>= 3 then
235 res
= sys
.system
("make -B -f {makename} -j 4 2>&1")
237 res
= sys
.system
("make -B -f {makename} -j 4 2>&1 >/dev/null")
240 toolcontext
.error
(null, "make failed! Error code: {res}.")
244 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
248 # Singleton that store the knowledge about the compilation process
250 # The main module of the program
251 var mainmodule
: MModule
253 # The result of the RTA (used to know live types and methods)
254 var runtime_type_analysis
: RapidTypeAnalysis
256 # The modeulbuilder used to know the model and the AST
257 var modelbuilder
: ModelBuilder
259 # Is hardening asked? (see --hardening)
260 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
262 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, modelbuilder
: ModelBuilder)
264 self.mainmodule
= mainmodule
265 self.runtime_type_analysis
= runtime_type_analysis
266 self.modelbuilder
= modelbuilder
267 self.live_primitive_types
= new Array[MClassType]
268 for t
in runtime_type_analysis
.live_types
do
269 if t
.ctype
!= "val*" then
270 self.live_primitive_types
.add
(t
)
275 # Subset of runtime_type_analysis.live_types that contains only primitive types
276 # Used to implement the equal test
277 var live_primitive_types
: Array[MClassType]
279 # runtime_functions that need to be compiled
280 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
282 # runtime_functions already seen (todo or done)
283 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
284 fun todo
(m
: AbstractRuntimeFunction)
286 if seen
.has
(m
) then return
291 # Where global declaration are stored (the main .h)
293 # FIXME: should not be a vistor but just somewhere to store lines
294 # FIXME: should not have a global .h since it does not help recompilations
295 var header
: nullable GlobalCompilerVisitor writable = null
297 # The list of all associated visitors
298 # Used to generate .c files
299 # FIXME: should not be vistors but just somewhere to store lines
300 private var visitors
: List[GlobalCompilerVisitor] = new List[GlobalCompilerVisitor]
302 # List of additional .c files required to compile (native interface)
303 var extern_bodies
= new ArraySet[String]
305 # Return the C symbol associated to a live type runtime
306 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
307 fun classid
(mtype
: MClassType): String
309 if self.classids
.has_key
(mtype
) then
310 return self.classids
[mtype
]
312 print
"No classid for {mtype}"
316 # Cache for classid (computed by declare_runtimeclass)
317 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
319 # Declare C structures and identifiers for a runtime class
320 fun declare_runtimeclass
(v
: GlobalCompilerVisitor, mtype
: MClassType)
322 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
323 v
.add_decl
("/* runtime class {mtype} */")
324 var idnum
= classids
.length
325 var idname
= "ID_" + mtype
.c_name
326 self.classids
[mtype
] = idname
327 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
329 v
.add_decl
("struct {mtype.c_name} \{")
330 v
.add_decl
("int classid; /* must be {idname} */")
332 if mtype
.mclass
.name
== "NativeArray" then
333 # NativeArrays are just a instance header followed by an array of values
334 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
337 if mtype
.ctype
!= "val*" then
338 # Is the Nit type is native then the struct is a box with two fields:
339 # * the `classid` to be polymorph
340 # * the `value` that contains the native value.
341 v
.add_decl
("{mtype.ctype} value;")
344 # Collect all attributes and associate them a field in the structure.
345 # Note: we do not try to optimize the order and helps CC to optimize the client code.
346 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
347 for p
in cd
.intro_mproperties
do
348 if not p
isa MAttribute then continue
349 var t
= p
.intro
.static_mtype
.as(not null)
350 t
= t
.anchor_to
(self.mainmodule
, mtype
)
351 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
357 # Generate the init-instance of a live type (allocate + init-instance)
358 fun generate_init_instance
(mtype
: MClassType)
360 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
361 assert mtype
.ctype
== "val*"
362 var v
= self.new_visitor
364 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
367 if is_native_array
then
373 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
374 v
.add_decl
("/* allocate {mtype} */")
375 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
376 var res
= v
.new_var
(mtype
)
378 if is_native_array
then
379 var mtype_elt
= mtype
.arguments
.first
380 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
382 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
384 v
.add
("{res}->classid = {self.classid(mtype)};")
386 self.generate_init_attr
(v
, res
, mtype
)
387 v
.add
("return {res};")
391 fun generate_check_init_instance
(mtype
: MClassType)
393 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
395 var v
= self.new_visitor
396 var res
= new RuntimeVariable("self", mtype
, mtype
)
397 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
398 v
.add_decl
("/* allocate {mtype} */")
399 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
400 self.generate_check_attr
(v
, res
, mtype
)
404 # Generate code that collect initialize the attributes on a new instance
405 fun generate_init_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
407 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
409 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
410 for npropdef
in n
.n_propdefs
do
411 if npropdef
isa AAttrPropdef then
412 npropdef
.init_expr
(v
, recv
)
418 # Generate a check-init-instance
419 fun generate_check_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
421 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
423 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
424 for npropdef
in n
.n_propdefs
do
425 if npropdef
isa AAttrPropdef then
426 npropdef
.check_expr
(v
, recv
)
432 fun generate_box_instance
(mtype
: MClassType)
434 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
435 assert mtype
.ctype
!= "val*"
436 var v
= self.new_visitor
438 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
439 v
.add_decl
("/* allocate {mtype} */")
440 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
441 v
.add
("struct {mtype.c_name}*res = GC_MALLOC(sizeof(struct {mtype.c_name}));")
442 v
.add
("res->classid = {self.classid(mtype)};")
443 v
.add
("res->value = value;")
444 v
.add
("return (val*)res;")
449 # look for a needed .h and .c file for a given .nit source-file
450 # FIXME: bad API, parameter should be a MModule, not its source-file
451 fun add_extern
(file
: String)
453 file
= file
.strip_extension
(".nit")
454 var tryfile
= file
+ ".nit.h"
455 if tryfile
.file_exists
then
456 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
458 tryfile
= file
+ "_nit.h"
459 if tryfile
.file_exists
then
460 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
462 tryfile
= file
+ ".nit.c"
463 if tryfile
.file_exists
then
464 self.extern_bodies
.add
(tryfile
)
466 tryfile
= file
+ "_nit.c"
467 if tryfile
.file_exists
then
468 self.extern_bodies
.add
(tryfile
)
472 # Initialize a visitor specific for a compiler engine
473 fun new_visitor
: GlobalCompilerVisitor do return new GlobalCompilerVisitor(self)
475 # Generate the main C function.
477 # allocate the Sys object if it exists
478 # call init if is exists
479 # call main if it exists
480 fun compile_main_function
482 var v
= self.new_visitor
483 v
.add_decl
("int glob_argc;")
484 v
.add_decl
("char **glob_argv;")
485 v
.add_decl
("val *glob_sys;")
486 v
.add_decl
("int main(int argc, char** argv) \{")
487 v
.add
("glob_argc = argc; glob_argv = argv;")
488 var main_type
= mainmodule
.sys_type
489 if main_type
!= null then
490 var mainmodule
= v
.compiler
.mainmodule
491 var glob_sys
= v
.init_instance
(main_type
)
492 v
.add
("glob_sys = {glob_sys};")
493 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
494 if main_init
!= null then
495 v
.send
(main_init
, [glob_sys
])
497 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
498 if main_method
!= null then
499 v
.send
(main_method
, [glob_sys
])
507 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
511 # Mangle a string to be a unique valid C identifier
512 fun to_cmangle
: String
515 var underscore
= false
517 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
523 res
.append
('_'.ascii
.to_s
)
526 if c
>= '0' and c
<= '9' then
529 else if c
== '_' then
534 res
.append
(c
.ascii
.to_s
)
542 # Escape " \ ' and non printable characters for literal C strings or characters
543 fun escape_to_c
: String
549 else if c
== '\0' then
551 else if c
== '"' then
553 else if c == '\'' then
555 else if c == '\\
' then
557 else if c.ascii < 32 then
558 b.append("\\{c.ascii.to_base(8, false)}")
568 # Return the C type associated to a given Nit static type
574 # Return the name of the C structure associated to a Nit live type
575 # FIXME: move to GlobalCompiler so we can check that self is a live type
576 fun c_name: String is abstract
577 protected var c_name_cache: nullable String protected writable
580 redef class MClassType
583 var res = self.c_name_cache
584 if res != null then return res
585 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
586 self.c_name_cache = res
590 redef fun ctype: String
592 if mclass.name == "Int" then
594 else if mclass.name == "Bool" then
596 else if mclass.name == "Char" then
598 else if mclass.name == "Float" then
600 else if mclass.name == "NativeString" then
602 else if mclass.name == "NativeArray" then
603 #return "{self.arguments.first.ctype}*"
605 else if mclass.kind == extern_kind then
613 redef class MGenericType
616 var res = self.c_name_cache
617 if res != null then return res
619 for t in self.arguments do
622 self.c_name_cache = res
627 redef class MParameterType
630 var res = self.c_name_cache
631 if res != null then return res
632 res = "FT{self.rank}"
633 self.c_name_cache = res
638 redef class MNullableType
641 var res = self.c_name_cache
642 if res != null then return res
643 res = "nullable_{self.mtype.c_name}"
644 self.c_name_cache = res
649 # A C function associated to a Nit method
650 # Because of customization, a given Nit method can be compiler more that once
651 abstract class AbstractRuntimeFunction
652 # The associated Nit method
653 var mmethoddef: MMethodDef
655 # The mangled c name of the runtime_function
656 # Subclasses should redefine `build_c_name` instead
659 var res = self.c_name_cache
660 if res != null then return res
661 res = self.build_c_name
662 self.c_name_cache = res
666 # Non cached version of `c_name`
667 protected fun build_c_name: String is abstract
669 private var c_name_cache: nullable String = null
671 # Implements a call of the runtime_function
672 # May inline the body or generate a C function call
673 fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
675 # Generate the code for the RuntimeFunction
676 # Warning: compile more than once compilation makes CC unhappy
677 fun compile_to_c(compiler: GlobalCompiler) is abstract
680 # A runtime function customized on a specific monomrph receiver type
681 private class CustomizedRuntimeFunction
682 super AbstractRuntimeFunction
684 # The considered reciever
685 # (usually is a live type but no strong guarantee)
688 init(mmethoddef: MMethodDef, recv: MClassType)
694 redef fun build_c_name: String
696 var res = self.c_name_cache
697 if res != null then return res
698 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
699 res = self.mmethoddef.c_name
701 res = "{mmethoddef.c_name}__{recv.c_name}"
703 self.c_name_cache = res
708 # used in the compiler worklist
710 if not o isa CustomizedRuntimeFunction then return false
711 if self.mmethoddef != o.mmethoddef then return false
712 if self.recv != o.recv then return false
717 # used in the compiler work-list
719 var res = self.mmethoddef.hash + self.recv.hash
725 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
726 return self.mmethoddef.to_s
728 return "{self.mmethoddef}@{self.recv}"
732 # compile the code customized for the reciever
733 redef fun compile_to_c(compiler)
736 var mmethoddef = self.mmethoddef
737 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
738 print("problem: why do we compile {self} for {recv}?")
742 var v = compiler.new_visitor
743 var selfvar = new RuntimeVariable("self", recv, recv)
744 if compiler.runtime_type_analysis.live_types.has(recv) then
745 selfvar.is_exact = true
747 var arguments = new Array[RuntimeVariable]
748 var frame = new Frame(v, mmethoddef, recv, arguments)
752 var comment = new Buffer
753 var ret = mmethoddef.msignature.return_mtype
755 ret = v.resolve_for(ret, selfvar)
756 sig.append("{ret.ctype} ")
757 else if mmethoddef.mproperty.is_new then
759 sig.append("{ret.ctype} ")
763 sig.append(self.c_name)
764 sig.append("({recv.ctype} {selfvar}")
765 comment.append("(self: {recv}")
766 arguments.add(selfvar)
767 for i in [0..mmethoddef.msignature.arity[ do
768 var mtype = mmethoddef.msignature.mparameters[i].mtype
769 if i == mmethoddef.msignature.vararg_rank then
770 mtype = v.get_class("Array").get_mtype([mtype])
772 mtype = v.resolve_for(mtype, selfvar)
773 comment.append(", {mtype}")
774 sig.append(", {mtype.ctype} p{i}")
775 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
776 arguments.add(argvar)
781 comment.append(": {ret}")
783 compiler.header.add_decl("{sig};")
785 v.add_decl("/* method {self} for {comment} */")
786 v.add_decl("{sig} \{")
787 #v.add("printf(\"method {self} for {comment}\\n\");")
789 frame.returnvar = v.new_var(ret)
791 frame.returnlabel = v.get_name("RET_LABEL")
793 mmethoddef.compile_inside_to_c(v, arguments)
795 v.add("{frame.returnlabel.as(not null)}:;")
797 v.add("return {frame.returnvar.as(not null)};")
802 redef fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
804 var ret = self.mmethoddef.msignature.return_mtype
805 if self.mmethoddef.mproperty.is_new then
809 ret = v.resolve_for(ret, arguments.first)
811 if self.mmethoddef.can_inline(v) then
812 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
813 frame.returnlabel = v.get_name("RET_LABEL")
815 frame.returnvar = v.new_var(ret)
817 var old_frame = v.frame
819 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
820 self.mmethoddef.compile_inside_to_c(v, arguments)
821 v.add("{frame.returnlabel.as(not null)}:(void)0;")
824 return frame.returnvar
826 v.adapt_signature(self.mmethoddef, arguments)
827 v.compiler.todo(self)
829 v.add("{self.c_name}({arguments.join(",")});")
832 var res = v.new_var(ret)
833 v.add("{res} = {self.c_name}({arguments.join(",")});")
839 # A runtime variable hold a runtime value in C.
840 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
842 # 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.
843 class RuntimeVariable
844 # The name of the variable in the C code
847 # The static type of the variable (as declard in C)
850 # The current casted type of the variable (as known in Nit)
851 var mcasttype: MType writable
853 # If the variable exaclty a mcasttype?
854 # false (usual value) means that the variable is a mcasttype or a subtype.
855 var is_exact: Bool writable = false
857 init(name: String, mtype: MType, mcasttype: MType)
861 self.mcasttype = mcasttype
862 assert not mtype.need_anchor
863 assert not mcasttype.need_anchor
866 redef fun to_s do return name
871 if self.is_exact then
877 if self.mtype == self.mcasttype then
878 type_str = "{mtype}{exact_str}"
880 type_str = "{mtype}({mcasttype}{exact_str})"
882 return "<{name}:{type_str}>"
886 # A visitor on the AST of property definition that generate the C code.
887 # Because of inlining, a visitor can visit more than one property.
888 class GlobalCompilerVisitor
889 # The associated compiler
890 var compiler: GlobalCompiler
892 init(compiler: GlobalCompiler)
894 self.compiler = compiler
895 compiler.visitors.add(self)
898 # Alias for self.compiler.mainmodule.object_type
899 fun object_type: MClassType do return self.compiler.mainmodule.object_type
901 # Alias for self.compiler.mainmodule.bool_type
902 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
904 # Force to get the primitive class named `name' or abort
905 fun get_class
(name
: String): MClass
907 return self.compiler
.mainmodule
.get_primitive_class
(name
)
910 # Force to get the primitive property named `name' in the instance `recv' or abort
911 fun get_property
(name
: String, recv
: MType): MMethod
913 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
, self.compiler
.mainmodule
)
917 var frame
: nullable Frame writable
919 # Anchor a type to the main module and the current receiver
920 fun anchor
(mtype
: MType): MType
922 if not mtype
.need_anchor
then return mtype
923 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
924 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
927 # Add a line in the main part of the generated C
934 # (used for local or global declaration)
935 fun add_decl
(s
: String)
937 self.decl_lines
.add
(s
)
940 private var lines
: List[String] = new List[String]
941 private var decl_lines
: List[String] = new List[String]
943 # The current visited AST node
944 var current_node
: nullable ANode = null
946 # Compile an expression an return its result
947 # `mtype` is the expected return type, pass null if no specific type is expected.
948 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
950 var old
= self.current_node
951 self.current_node
= nexpr
952 var res
= nexpr
.expr
(self).as(not null)
953 if mtype
!= null then
954 mtype
= self.anchor
(mtype
)
955 res
= self.autobox
(res
, mtype
)
957 var implicit_cast_to
= nexpr
.implicit_cast_to
958 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
959 var castres
= self.type_test
(res
, implicit_cast_to
)
960 self.add
("if (!{castres}) \{")
961 self.add_abort
("Cast failed")
964 self.current_node
= old
968 # Unsafely cast a value to a new type
969 # ie the result share the same C variable but my have a different mcasttype
970 # NOTE: if the adaptation is useless then `value' is returned as it.
971 # ENSURE: return.name == value.name
972 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
974 mtype
= self.anchor
(mtype
)
975 var valmtype
= value
.mcasttype
976 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
980 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
981 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
984 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
989 # Box or unbox a value to another type iff a C type conversion is needed
990 # ENSURE: result.mtype.ctype == mtype.ctype
991 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
993 if value
.mtype
== mtype
then
995 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
997 else if value
.mtype
.ctype
== "val*" then
998 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
999 else if mtype
.ctype
== "val*" then
1000 var valtype
= value
.mtype
.as(MClassType)
1001 var res
= self.new_var
(mtype
)
1002 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
1003 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
1004 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
1007 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
1010 # Bad things will appen!
1011 var res
= self.new_var
(mtype
)
1012 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
1013 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
1018 # Correctly assign a left and a right value
1019 # Boxing and unboxing is performed if required
1020 fun assign
(left
, right
: RuntimeVariable)
1022 right
= self.autobox
(right
, left
.mtype
)
1023 self.add
("{left} = {right};")
1027 # Alias for `self.expr(nexpr, self.bool_type)'
1028 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
1030 return expr
(nexpr
, bool_type
)
1033 # Compile a statement (if any)
1034 fun stmt
(nexpr
: nullable AExpr)
1036 if nexpr
== null then return
1037 var old
= self.current_node
1038 self.current_node
= nexpr
1040 self.current_node
= old
1043 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1044 fun debug
(message
: String)
1046 var node
= self.current_node
1047 if node
== null then
1048 print
"?: {message}"
1052 self.add
("/* DEBUG: {message} */")
1055 # Return a new uninitialized local runtime_variable
1056 fun new_var
(mtype
: MType): RuntimeVariable
1058 mtype
= self.anchor
(mtype
)
1059 var name
= self.get_name
("var")
1060 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1061 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1065 # Return a new uninitialized named runtime_variable
1066 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
1068 mtype
= self.anchor
(mtype
)
1069 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1070 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1074 # Return a new local runtime_variable initialized with the C expression `cexpr'.
1075 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
1077 var res
= new_var
(mtype
)
1078 self.add
("{res} = {cexpr};")
1082 # Return the local runtime_variable associated to a Nit local variable
1083 fun variable
(variable
: Variable): RuntimeVariable
1085 if self.variables
.has_key
(variable
) then
1086 return self.variables
[variable
]
1088 var name
= self.get_name
("var_{variable.name}")
1089 var mtype
= variable
.declared_type
.as(not null)
1090 mtype
= self.anchor
(mtype
)
1091 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1092 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1093 self.variables
[variable
] = res
1098 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
1100 # Return an unique and stable identifier associated with an escapemark
1101 fun escapemark_name
(e
: nullable EscapeMark): String
1104 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
1106 if name
== null then name
= "label"
1107 name
= get_name
(name
)
1108 escapemark_names
[e
] = name
1112 private var escapemark_names
= new HashMap[EscapeMark, String]
1114 # Return a new name based on `s' and unique in the visitor
1115 fun get_name
(s
: String): String
1117 if not self.names
.has
(s
) then
1121 var i
= self.last
+ 1
1124 if not self.names
.has
(s2
) then
1133 private var last
: Int = 0
1135 private var names
: HashSet[String] = new HashSet[String]
1137 # Generate a return with the value `s'
1138 fun ret
(s
: RuntimeVariable)
1140 self.assign
(self.frame
.returnvar
.as(not null), s
)
1141 self.add
("goto {self.frame.returnlabel.as(not null)};")
1144 # The runtime types that are acceptable for a given receiver.
1145 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
1147 var mtype
= recv
.mcasttype
1148 if recv
.is_exact
then
1149 assert mtype
isa MClassType
1150 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
1154 var cache
= self.compiler
.collect_types_cache
1155 if cache
.has_key
(mtype
) then
1158 var types
= new Array[MClassType]
1159 var mainmodule
= self.compiler
.mainmodule
1160 for t
in self.compiler
.runtime_type_analysis
.live_types
do
1161 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
1164 cache
[mtype
] = types
1168 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
1170 if not mtype
.need_anchor
then return mtype
1171 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
1172 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
1176 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable])
1178 var elttype
= arguments
.first
.mtype
1179 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
1180 if pname
== "[]" then
1181 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1183 else if pname
== "[]=" then
1184 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1186 else if pname
== "copy_to" then
1187 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
1188 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
1193 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable])
1195 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
1198 # Add a check and an abort for a null reciever is needed
1199 fun check_recv_notnull
(recv
: RuntimeVariable)
1201 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
1203 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
1205 self.add
("if ({recv} == NULL) \{")
1206 self.add_abort
("Reciever is null")
1211 # Generate a polymorphic send for the method `m' and the arguments `args'
1212 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1214 var types
= self.collect_types
(args
.first
)
1216 var res
: nullable RuntimeVariable
1217 var ret
= m
.intro
.msignature
.return_mtype
1219 ret
= args
.first
.mtype
1220 res
= self.new_var
(ret
)
1221 else if ret
== null then
1224 ret
= self.resolve_for
(ret
, args
.first
)
1225 res
= self.new_var
(ret
)
1228 self.add
("/* send {m} on {args.first.inspect} */")
1229 if args
.first
.mtype
.ctype
!= "val*" then
1230 var mclasstype
= args
.first
.mtype
.as(MClassType)
1231 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
1232 self.add
("/* skip, no method {m} */")
1235 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, mclasstype
)
1236 if propdefs
.length
== 0 then
1237 self.add
("/* skip, no method {m} */")
1240 assert propdefs
.length
== 1
1241 var propdef
= propdefs
.first
1242 var res2
= self.call
(propdef
, mclasstype
, args
)
1243 if res
!= null then self.assign
(res
, res2
.as(not null))
1246 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
1247 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
1248 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
1249 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
1250 if m
.name
== "==" then
1252 if args
[1].mcasttype
isa MNullableType then
1253 self.add
("{res} = ({args[1]} == NULL);")
1254 else if args
[1].mcasttype
isa MNullType then
1255 self.add
("{res} = 1; /* is null */")
1257 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
1259 else if m
.name
== "!=" then
1261 if args
[1].mcasttype
isa MNullableType then
1262 self.add
("{res} = ({args[1]} != NULL);")
1263 else if args
[1].mcasttype
isa MNullType then
1264 self.add
("{res} = 0; /* is null */")
1266 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
1269 self.add_abort
("Reciever is null")
1273 if types
.is_empty
then
1275 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
1276 self.bugtype
(args
.first
)
1281 self.add
("switch({args.first}->classid) \{")
1282 var last
= types
.last
1283 var defaultpropdef
: nullable MMethodDef = null
1285 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
1286 if propdefs
.length
== 0 then
1287 self.add
("/* skip {t}, no method {m} */")
1290 if propdefs
.length
> 1 then
1291 self.debug
("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
1293 var propdef
= propdefs
.first
1294 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
1295 defaultpropdef
= propdef
1298 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
1299 self.add
("default: /* test {t} */")
1301 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
1303 var res2
= self.call
(propdef
, t
, args
)
1304 if res
!= null then self.assign
(res
, res2
.as(not null))
1307 if defaultpropdef
!= null then
1308 self.add
("default: /* default is Object */")
1309 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
1310 if res
!= null then self.assign
(res
, res2
.as(not null))
1311 else if self.compiler
.hardening
then
1312 self.add
("default: /* bug */")
1313 self.bugtype
(args
.first
)
1319 # Generate a monomorphic send for the method `m', the type `t' and the arguments `args'
1320 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1322 assert t
isa MClassType
1323 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
1324 if propdefs
.length
== 0 then
1327 if propdefs
.length
> 1 then
1328 self.debug
("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
1330 var propdef
= propdefs
.first
1331 return self.call
(propdef
, t
, args
)
1334 fun check_valid_reciever
(recvtype
: MClassType)
1336 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
1337 print
"{recvtype} is not a live type"
1341 # Generate a static call on a method definition
1342 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1344 check_valid_reciever
(recvtype
)
1345 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
1346 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
1347 recvtype
= m
.mclassdef
.bound_mtype
1349 var recv
= self.autobox
(args
.first
, recvtype
)
1350 recv
= self.autoadapt
(recv
, recvtype
)
1353 self.varargize
(m
.msignature
.as(not null), args
)
1354 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
1355 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); exit(1);")
1356 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
1361 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
1362 return rm
.call
(self, args
)
1365 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
1367 var recv
= args
.first
1368 for i
in [0..m
.msignature
.arity
[ do
1369 var t
= m
.msignature
.mparameters
[i
].mtype
1370 if i
== m
.msignature
.vararg_rank
then
1373 t
= self.resolve_for
(t
, recv
)
1374 args
[i
+1] = self.autobox
(args
[i
+1], t
)
1378 # Transform varargs, in raw arguments, into a single argument of type Array
1379 # Note: this method modify the given `args`
1380 # If there is no vararg, then `args` is not modified.
1381 fun varargize
(msignature
: MSignature, args
: Array[RuntimeVariable])
1383 var recv
= args
.first
1384 var vararg_rank
= msignature
.vararg_rank
1385 if vararg_rank
>= 0 then
1386 assert args
.length
>= msignature
.arity
+ 1 # because of self
1388 args
= new Array[RuntimeVariable]
1390 args
.add
(rawargs
.first
) # recv
1392 for i
in [0..vararg_rank
[ do
1393 args
.add
(rawargs
[i
+1])
1396 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-msignature
.arity
1397 var vararg
= new Array[RuntimeVariable]
1398 for i
in [vararg_rank
..vararg_lastrank
] do
1399 vararg
.add
(rawargs
[i
+1])
1401 # FIXME: its it to late to determine the vararg type, this should have been done during a previous analysis
1402 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
1403 elttype
= self.resolve_for
(elttype
, recv
)
1404 args
.add
(self.array_instance
(vararg
, elttype
))
1406 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
1407 args
.add
(rawargs
[i
+1])
1410 rawargs
.add_all
(args
)
1414 fun bugtype
(recv
: RuntimeVariable)
1416 if recv
.mtype
.ctype
!= "val*" then return
1417 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
1418 self.add
("exit(1);")
1421 # Generate a polymorphic attribute is_set test
1422 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1424 check_recv_notnull
(recv
)
1426 var types
= self.collect_types
(recv
)
1428 var res
= self.new_var
(bool_type
)
1430 if types
.is_empty
then
1431 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1435 self.add
("/* isset {a} on {recv.inspect} */")
1436 self.add
("switch({recv}->classid) \{")
1437 var last
= types
.last
1439 if not self.compiler
.hardening
and t
== last
then
1440 self.add
("default: /*{self.compiler.classid(t)}*/")
1442 self.add
("case {self.compiler.classid(t)}:")
1444 var recv2
= self.autoadapt
(recv
, t
)
1445 var ta
= a
.intro
.static_mtype
.as(not null)
1446 ta
= self.resolve_for
(ta
, recv2
)
1447 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1448 if not ta
isa MNullableType then
1449 if ta
.ctype
== "val*" then
1450 self.add
("{res} = ({attr} != NULL);")
1452 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
1457 if self.compiler
.hardening
then
1458 self.add
("default: /* Bug */")
1466 # Generate a polymorphic attribute read
1467 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1469 check_recv_notnull
(recv
)
1471 var types
= self.collect_types
(recv
)
1473 var ret
= a
.intro
.static_mtype
.as(not null)
1474 ret
= self.resolve_for
(ret
, recv
)
1475 var res
= self.new_var
(ret
)
1477 if types
.is_empty
then
1478 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1482 self.add
("/* read {a} on {recv.inspect} */")
1483 self.add
("switch({recv}->classid) \{")
1484 var last
= types
.last
1486 if not self.compiler
.hardening
and t
== last
then
1487 self.add
("default: /*{self.compiler.classid(t)}*/")
1489 self.add
("case {self.compiler.classid(t)}:")
1491 var recv2
= self.autoadapt
(recv
, t
)
1492 var ta
= a
.intro
.static_mtype
.as(not null)
1493 ta
= self.resolve_for
(ta
, recv2
)
1494 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1495 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
1496 if ta
.ctype
== "val*" then
1497 self.add
("if ({res2} == NULL) \{")
1498 self.add_abort
("Uninitialized attribute {a.name}")
1501 self.add
("/*NOTYET isset on primitive attributes*/")
1504 self.assign
(res
, res2
)
1507 if self.compiler
.hardening
then
1508 self.add
("default: /* Bug */")
1516 # Generate a polymorphic attribute write
1517 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1519 check_recv_notnull
(recv
)
1521 var types
= self.collect_types
(recv
)
1523 if types
.is_empty
then
1524 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1528 self.add
("/* write {a} on {recv.inspect} */")
1529 self.add
("switch({recv}->classid) \{")
1530 var last
= types
.last
1532 if not self.compiler
.hardening
and t
== last
then
1533 self.add
("default: /*{self.compiler.classid(t)}*/")
1535 self.add
("case {self.compiler.classid(t)}:")
1537 var recv2
= self.autoadapt
(recv
, t
)
1538 var ta
= a
.intro
.static_mtype
.as(not null)
1539 ta
= self.resolve_for
(ta
, recv2
)
1540 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1543 if self.compiler
.hardening
then
1544 self.add
("default: /* Bug*/")
1550 # Generate a alloc-instance + init-attributes
1551 fun init_instance
(mtype
: MClassType): RuntimeVariable
1553 mtype
= self.anchor
(mtype
).as(MClassType)
1554 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1555 debug
"problem: {mtype} was detected dead"
1557 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1562 # Generate a polymorphic subtype test
1563 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1565 mtype
= self.anchor
(mtype
)
1566 var mclasstype
= mtype
1567 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
1568 assert mclasstype
isa MClassType
1569 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
1570 debug
"problem: {mtype} was detected cast-dead"
1574 var types
= self.collect_types
(value
)
1576 var res
= self.new_var
(bool_type
)
1578 self.add
("/* isa {mtype} on {value.inspect} */")
1579 if value
.mtype
.ctype
!= "val*" then
1580 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1581 self.add
("{res} = 1;")
1583 self.add
("{res} = 0;")
1587 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
1588 self.add
("if ({value} == NULL) \{")
1589 if mtype
isa MNullableType then
1590 self.add
("{res} = 1; /* isa {mtype} */")
1592 self.add
("{res} = 0; /* not isa {mtype} */")
1594 self.add
("\} else ")
1596 self.add
("switch({value}->classid) \{")
1598 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1599 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1602 self.add
("{res} = 1;")
1604 self.add
("default:")
1605 self.add
("{res} = 0;")
1611 # Generate the code required to dynamically check if 2 objects share the same runtime type
1612 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1614 var res
= self.new_var
(bool_type
)
1615 if value2
.mtype
.ctype
== "val*" then
1616 if value1
.mtype
.ctype
== "val*" then
1617 self.add
"{res} = {value1}->classid == {value2}->classid;"
1619 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
1622 if value1
.mtype
.ctype
== "val*" then
1623 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
1624 else if value1
.mcasttype
== value2
.mcasttype
then
1625 self.add
"{res} = 1;"
1627 self.add
"{res} = 0;"
1633 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1634 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
1635 fun class_name_string
(value
: RuntimeVariable): String
1637 var res
= self.get_name
("var_class_name")
1638 self.add_decl
("const char* {res};")
1639 if value
.mtype
.ctype
== "val*" then
1640 self.add
"{res} = class_names[{value}->classid];"
1642 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
1647 # Generate a Nit "is" for two runtime_variables
1648 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1650 var res
= self.new_var
(bool_type
)
1651 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1656 if value1
.mtype
.ctype
!= "val*" then
1657 if value2
.mtype
== value1
.mtype
then
1658 self.add
("{res} = {value1} == {value2};")
1659 else if value2
.mtype
.ctype
!= "val*" then
1660 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1662 var mtype1
= value1
.mtype
.as(MClassType)
1663 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1664 self.add
("if ({res}) \{")
1665 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1669 var s
= new Array[String]
1670 for t
in self.compiler
.live_primitive_types
do
1671 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1672 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1673 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1676 self.add
("{res} = {value1} == {value2};")
1678 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1684 # Generate a check-init-instance
1685 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType)
1687 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1689 mtype
= self.anchor
(mtype
).as(MClassType)
1690 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1691 debug
"problem: {mtype} was detected dead"
1694 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
1697 # Generate an integer value
1698 fun int_instance
(value
: Int): RuntimeVariable
1700 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1701 self.add
("{res} = {value};")
1705 # Generate an array value
1706 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1708 elttype
= self.anchor
(elttype
)
1709 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
1710 var res
= self.init_instance
(arraytype
)
1711 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1712 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1714 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1715 for i
in [0..array
.length
[ do
1716 var r
= self.autobox
(array
[i
], elttype
)
1717 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1719 var length
= self.int_instance
(array
.length
)
1720 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1721 self.check_init_instance
(res
, arraytype
)
1726 # Generate a string value
1727 fun string_instance
(string
: String): RuntimeVariable
1729 var mtype
= self.get_class
("String").mclass_type
1730 var name
= self.get_name
("varonce")
1731 self.add_decl
("static {mtype.ctype} {name};")
1732 var res
= self.new_var
(mtype
)
1733 self.add
("if ({name}) \{")
1734 self.add
("{res} = {name};")
1735 self.add
("\} else \{")
1736 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1737 self.add
("{nat} = \"{string.escape_to_c}\
";")
1738 var res2
= self.init_instance
(mtype
)
1739 self.add
("{res} = {res2};")
1740 var length
= self.int_instance
(string
.length
)
1741 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
1742 self.check_init_instance
(res
, mtype
)
1743 self.add
("{name} = {res};")
1748 # Generate generic abort
1749 # used by aborts, asserts, casts, etc.
1750 fun add_abort
(message
: String)
1752 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1753 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});")
1755 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
1757 self.add
("exit(1);")
1761 # A frame correspond to a visited property in a GlobalCompilerVisitor
1763 # The associated visitor
1765 var visitor
: GlobalCompilerVisitor
1767 # The executed property.
1768 # A Method in case of a call, an attribute in case of a default initialization.
1769 var mpropdef
: MPropDef
1771 # The static type of the receiver
1772 var receiver
: MClassType
1774 # Arguments of the method (the first is the receiver)
1775 var arguments
: Array[RuntimeVariable]
1777 # The runtime_variable associated to the return (in a function)
1778 var returnvar
: nullable RuntimeVariable writable = null
1780 # The label at the end of the property
1781 var returnlabel
: nullable String writable = null
1784 redef class MPropDef
1785 private var c_name_cache
: nullable String
1787 # The mangled name associated to the property
1790 var res
= self.c_name_cache
1791 if res
!= null then return res
1792 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1793 self.c_name_cache
= res
1798 redef class MMethodDef
1799 # Can the body be inlined?
1800 fun can_inline
(v
: GlobalCompilerVisitor): Bool
1802 var modelbuilder
= v
.compiler
.modelbuilder
1803 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1804 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1805 return npropdef
.can_inline
1806 else if self.mproperty
.name
== "init" then
1807 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1814 # Inline the body in another visitor
1815 fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1817 var modelbuilder
= v
.compiler
.modelbuilder
1818 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1819 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1820 var oldnode
= v
.current_node
1821 v
.current_node
= npropdef
1822 self.compile_parameter_check
(v
, arguments
)
1823 npropdef
.compile_to_c
(v
, self, arguments
)
1824 v
.current_node
= oldnode
1825 else if self.mproperty
.name
== "init" then
1826 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1827 var oldnode
= v
.current_node
1828 v
.current_node
= nclassdef
1829 self.compile_parameter_check
(v
, arguments
)
1830 nclassdef
.compile_to_c
(v
, self, arguments
)
1831 v
.current_node
= oldnode
1838 # Generate type checks in the C code to check covariant parameters
1839 fun compile_parameter_check
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable])
1841 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_covariance
.value
then return
1843 for i
in [0..msignature
.arity
[ do
1844 # skip test for vararg since the array is instantiated with the correct polymorphic type
1845 if msignature
.vararg_rank
== i
then continue
1847 # skip if the cast is not required
1848 var origmtype
= self.mproperty
.intro
.msignature
.mparameters
[i
].mtype
1849 if not origmtype
.need_anchor
then continue
1851 # get the parameter type
1852 var mtype
= self.msignature
.mparameters
[i
].mtype
1855 # note that v decides if and how to implements the cast
1856 v
.add
("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1857 var cond
= v
.type_test
( arguments
[i
+1], mtype
)
1858 v
.add
("if (!{cond}) \{")
1859 #var x = v.class_name_string(arguments[i+1])
1860 #var y = v.class_name_string(arguments.first)
1861 #v.add("fprintf(stderr, \"expected {mtype} (self is %s), got %s for {arguments[i+1].inspect}\\n\", {y}, {x});")
1862 v
.add_abort
("Cast failed")
1868 redef class APropdef
1869 fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1871 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
1872 debug
("Not yet implemented")
1875 fun can_inline
: Bool do return true
1878 redef class AConcreteMethPropdef
1879 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1881 for i
in [0..mpropdef
.msignature
.arity
[ do
1882 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1883 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1885 # Call the implicit super-init
1886 var auto_super_inits
= self.auto_super_inits
1887 if auto_super_inits
!= null then
1888 var selfarg
= [arguments
.first
]
1889 for auto_super_init
in auto_super_inits
do
1890 if auto_super_init
.intro
.msignature
.arity
== 0 then
1891 v
.send
(auto_super_init
, selfarg
)
1893 v
.send
(auto_super_init
, arguments
)
1897 v
.stmt
(self.n_block
)
1900 redef fun can_inline
1902 if self.auto_super_inits
!= null then return false
1903 var nblock
= self.n_block
1904 if nblock
== null then return true
1905 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
1906 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
1911 redef class AInternMethPropdef
1912 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1914 var pname
= mpropdef
.mproperty
.name
1915 var cname
= mpropdef
.mclassdef
.mclass
.name
1916 var ret
= mpropdef
.msignature
.return_mtype
1918 ret
= v
.resolve_for
(ret
, arguments
.first
)
1920 if pname
!= "==" and pname
!= "!=" then
1921 v
.adapt_signature
(mpropdef
, arguments
)
1923 if cname
== "Int" then
1924 if pname
== "output" then
1925 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1927 else if pname
== "object_id" then
1928 v
.ret
(arguments
.first
)
1930 else if pname
== "+" then
1931 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1933 else if pname
== "-" then
1934 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1936 else if pname
== "unary -" then
1937 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1939 else if pname
== "succ" then
1940 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1942 else if pname
== "prec" then
1943 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1945 else if pname
== "*" then
1946 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1948 else if pname
== "/" then
1949 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1951 else if pname
== "%" then
1952 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1954 else if pname
== "lshift" then
1955 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1957 else if pname
== "rshift" then
1958 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1960 else if pname
== "==" then
1961 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1963 else if pname
== "!=" then
1964 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1965 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1967 else if pname
== "<" then
1968 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1970 else if pname
== ">" then
1971 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1973 else if pname
== "<=" then
1974 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1976 else if pname
== ">=" then
1977 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1979 else if pname
== "to_f" then
1980 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1982 else if pname
== "ascii" then
1983 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1986 else if cname
== "Char" then
1987 if pname
== "output" then
1988 v
.add
("printf(\"%c\
", {arguments.first});")
1990 else if pname
== "object_id" then
1991 v
.ret
(arguments
.first
)
1993 else if pname
== "+" then
1994 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1996 else if pname
== "-" then
1997 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1999 else if pname
== "==" then
2000 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2002 else if pname
== "!=" then
2003 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2004 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2006 else if pname
== "succ" then
2007 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2009 else if pname
== "prec" then
2010 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
2012 else if pname
== "<" then
2013 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2015 else if pname
== ">" then
2016 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2018 else if pname
== "<=" then
2019 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", 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
== "to_i" then
2025 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
2027 else if pname
== "ascii" then
2028 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2031 else if cname
== "Bool" then
2032 if pname
== "output" then
2033 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
2035 else if pname
== "object_id" then
2036 v
.ret
(arguments
.first
)
2038 else if pname
== "==" then
2039 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2041 else if pname
== "!=" then
2042 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2043 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2046 else if cname
== "Float" then
2047 if pname
== "output" then
2048 v
.add
("printf(\"%f\\n\
", {arguments.first});")
2050 else if pname
== "object_id" then
2051 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
2053 else if pname
== "+" then
2054 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2056 else if pname
== "-" then
2057 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2059 else if pname
== "unary -" then
2060 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2062 else if pname
== "succ" then
2063 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2065 else if pname
== "prec" then
2066 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
2068 else if pname
== "*" then
2069 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2071 else if pname
== "/" then
2072 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2074 else if pname
== "==" then
2075 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2077 else if pname
== "!=" then
2078 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2079 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2081 else if pname
== "<" then
2082 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2084 else if pname
== ">" then
2085 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2087 else if pname
== "<=" then
2088 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2090 else if pname
== ">=" then
2091 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2093 else if pname
== "to_i" then
2094 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2097 else if cname
== "Char" then
2098 if pname
== "output" then
2099 v
.add
("printf(\"%c\
", {arguments.first});")
2101 else if pname
== "object_id" then
2102 v
.ret
(arguments
.first
)
2104 else if pname
== "==" then
2105 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2107 else if pname
== "!=" then
2108 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2109 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2111 else if pname
== "ascii" then
2112 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
2115 else if cname
== "NativeString" then
2116 if pname
== "[]" then
2117 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
2119 else if pname
== "[]=" then
2120 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2122 else if pname
== "copy_to" then
2123 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2125 else if pname
== "atoi" then
2126 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
2129 else if cname
== "NativeArray" then
2130 v
.native_array_def
(pname
, ret
, arguments
)
2133 if pname
== "exit" then
2134 v
.add
("exit({arguments[1]});")
2136 else if pname
== "sys" then
2137 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
2139 else if pname
== "calloc_string" then
2140 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
2142 else if pname
== "calloc_array" then
2143 v
.calloc_array
(ret
.as(not null), arguments
)
2145 else if pname
== "object_id" then
2146 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2148 else if pname
== "is_same_type" then
2149 v
.ret
(v
.is_same_type_test
(arguments
[0], arguments
[1]))
2151 else if pname
== "output_class_name" then
2152 var nat
= v
.class_name_string
(arguments
.first
)
2153 v
.add
("printf(\"%s\\n\
", {nat});")
2155 else if pname
== "native_class_name" then
2156 var nat
= v
.class_name_string
(arguments
.first
)
2157 v
.ret
(v
.new_expr
("(char*){nat}", ret
.as(not null)))
2159 else if pname
== "force_garbage_collection" then
2160 v
.add
("GC_gcollect();")
2163 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at
{location.to_s}\\n\
");")
2164 debug
("Not implemented {mpropdef}")
2168 redef class AExternMethPropdef
2169 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2172 var nextern
= self.n_extern
2173 if nextern
== null then
2174 v
.add
("fprintf(stderr, \"NOT YET IMPLEMENTED nitni
for {mpropdef} at
{location.to_s}\\n\
");")
2178 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2179 if location
.file
!= null then
2180 var file
= location
.file
.filename
2181 v
.compiler
.add_extern
(file
)
2183 var res
: nullable RuntimeVariable = null
2184 var ret
= mpropdef
.msignature
.return_mtype
2186 ret
= v
.resolve_for
(ret
, arguments
.first
)
2187 res
= v
.new_var
(ret
)
2189 v
.adapt_signature
(mpropdef
, arguments
)
2192 v
.add
("{externname}({arguments.join(", ")});")
2194 v
.add
("{res} = {externname}({arguments.join(", ")});")
2200 redef class AExternInitPropdef
2201 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2204 var nextern
= self.n_extern
2205 if nextern
== null then
2206 debug
("{mpropdef} need extern name")
2209 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2210 if location
.file
!= null then
2211 var file
= location
.file
.filename
2212 v
.compiler
.add_extern
(file
)
2214 v
.adapt_signature
(mpropdef
, arguments
)
2215 var ret
= arguments
.first
.mtype
2216 var res
= v
.new_var
(ret
)
2220 v
.add
("{res} = {externname}({arguments.join(", ")});")
2225 redef class AAttrPropdef
2226 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2228 if arguments
.length
== 1 then
2229 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
2230 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
2232 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
2236 fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2238 var nexpr
= self.n_expr
2239 if nexpr
!= null then
2240 var oldnode
= v
.current_node
2241 v
.current_node
= self
2242 var old_frame
= v
.frame
2243 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2245 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
2246 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
2248 v
.current_node
= oldnode
2252 fun check_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2254 var nexpr
= self.n_expr
2255 if nexpr
!= null then return
2257 var oldnode
= v
.current_node
2258 v
.current_node
= self
2259 var old_frame
= v
.frame
2260 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2262 # Force read to check the initialization
2263 v
.read_attribute
(self.mpropdef
.mproperty
, recv
)
2265 v
.current_node
= oldnode
2269 redef class AClassdef
2270 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
2272 if mpropdef
== self.mfree_init
then
2273 var super_inits
= self.super_inits
2274 if super_inits
!= null then
2275 assert arguments
.length
== 1
2276 for su
in super_inits
do
2277 v
.send
(su
, arguments
)
2281 var recv
= arguments
.first
2283 # Collect undefined attributes
2284 for npropdef
in self.n_propdefs
do
2285 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
2286 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
2296 redef class ADeferredMethPropdef
2297 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2299 v
.add_abort
("Deferred method called")
2302 redef fun can_inline
do return true
2306 # Try to compile self as an expression
2307 # Do not call this method directly, use `v.expr' instead
2308 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
2310 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
2311 var mtype
= self.mtype
2312 if mtype
== null then
2315 var res
= v
.new_var
(mtype
)
2316 v
.add
("/* {res} = NOT YET {class_name} */")
2321 # Try to compile self as a statement
2322 # Do not call this method directly, use `v.stmt' instead
2323 private fun stmt
(v
: GlobalCompilerVisitor)
2326 if res
!= null then v
.add
("{res};")
2331 redef class ABlockExpr
2334 for e
in self.n_expr
do
2340 redef class AVardeclExpr
2343 var variable
= self.variable
.as(not null)
2344 var ne
= self.n_expr
2346 var i
= v
.expr
(ne
, variable
.declared_type
)
2347 v
.assign
(v
.variable
(variable
), i
)
2352 redef class AVarExpr
2355 var res
= v
.variable
(self.variable
.as(not null))
2356 var mtype
= self.mtype
.as(not null)
2357 return v
.autoadapt
(res
, mtype
)
2361 redef class AVarAssignExpr
2364 var variable
= self.variable
.as(not null)
2365 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
2366 v
.assign
(v
.variable
(variable
), i
)
2370 redef class AVarReassignExpr
2373 var variable
= self.variable
.as(not null)
2374 var vari
= v
.variable
(variable
)
2375 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
2376 var res
= v
.send
(reassign_property
.mproperty
, [vari
, value
])
2378 v
.assign
(v
.variable
(variable
), res
)
2382 redef class ASelfExpr
2385 return v
.frame
.arguments
.first
2389 redef class AContinueExpr
2392 v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
2396 redef class ABreakExpr
2399 v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
2403 redef class AReturnExpr
2406 var nexpr
= self.n_expr
2407 if nexpr
!= null then
2408 var returnvar
= v
.frame
.returnvar
.as(not null)
2409 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
2410 v
.assign
(returnvar
, i
)
2412 v
.add
("goto {v.frame.returnlabel.as(not null)};")
2416 redef class AAbortExpr
2419 v
.add_abort
("Aborted")
2426 var cond
= v
.expr_bool
(self.n_expr
)
2427 v
.add
("if ({cond})\{")
2435 redef class AIfexprExpr
2438 var res
= v
.new_var
(self.mtype
.as(not null))
2439 var cond
= v
.expr_bool
(self.n_expr
)
2440 v
.add
("if ({cond})\{")
2441 v
.assign
(res
, v
.expr
(self.n_then
, null))
2443 v
.assign
(res
, v
.expr
(self.n_else
, null))
2452 v
.stmt
(self.n_block
)
2453 var escapemark
= self.escapemark
2454 if escapemark
!= null then
2455 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2460 redef class AWhileExpr
2464 var cond
= v
.expr_bool
(self.n_expr
)
2465 v
.add
("if (!{cond}) break;")
2466 v
.stmt
(self.n_block
)
2467 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2469 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2473 redef class ALoopExpr
2477 v
.stmt
(self.n_block
)
2478 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2480 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2484 redef class AForExpr
2487 var cl
= v
.expr
(self.n_expr
, null)
2488 var it_meth
= self.method_iterator
2489 assert it_meth
!= null
2490 var it
= v
.send
(it_meth
, [cl
])
2493 var isok_meth
= self.method_is_ok
2494 assert isok_meth
!= null
2495 var ok
= v
.send
(isok_meth
, [it
])
2497 v
.add
("if(!{ok}) break;")
2498 if self.variables
.length
== 1 then
2499 var item_meth
= self.method_item
2500 assert item_meth
!= null
2501 var i
= v
.send
(item_meth
, [it
])
2503 v
.assign
(v
.variable
(variables
.first
), i
)
2504 else if self.variables
.length
== 2 then
2505 var key_meth
= self.method_key
2506 assert key_meth
!= null
2507 var i
= v
.send
(key_meth
, [it
])
2509 v
.assign
(v
.variable
(variables
[0]), i
)
2510 var item_meth
= self.method_item
2511 assert item_meth
!= null
2512 i
= v
.send
(item_meth
, [it
])
2514 v
.assign
(v
.variable
(variables
[1]), i
)
2518 v
.stmt
(self.n_block
)
2519 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2520 var next_meth
= self.method_next
2521 assert next_meth
!= null
2522 v
.send
(next_meth
, [it
])
2524 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2528 redef class AAssertExpr
2531 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
2533 var cond
= v
.expr_bool
(self.n_expr
)
2534 v
.add
("if (!{cond}) \{")
2538 v
.add_abort
("Assert '{nid.text}' failed")
2540 v
.add_abort
("Assert failed")
2549 var res
= v
.new_var
(self.mtype
.as(not null))
2550 var i1
= v
.expr_bool
(self.n_expr
)
2551 v
.add
("if ({i1}) \{")
2554 var i2
= v
.expr_bool
(self.n_expr2
)
2555 v
.add
("{res} = {i2};")
2561 redef class AAndExpr
2564 var res
= v
.new_var
(self.mtype
.as(not null))
2565 var i1
= v
.expr_bool
(self.n_expr
)
2566 v
.add
("if (!{i1}) \{")
2569 var i2
= v
.expr_bool
(self.n_expr2
)
2570 v
.add
("{res} = {i2};")
2576 redef class ANotExpr
2579 var cond
= v
.expr_bool
(self.n_expr
)
2580 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2584 redef class AOrElseExpr
2587 var res
= v
.new_var
(self.mtype
.as(not null))
2588 var i1
= v
.expr
(self.n_expr
, null)
2589 v
.add
("if ({i1}!=NULL) \{")
2592 var i2
= v
.expr
(self.n_expr2
, null)
2602 var value1
= v
.expr
(self.n_expr
, null)
2603 var value2
= v
.expr
(self.n_expr2
, null)
2604 return v
.equal_test
(value1
, value2
)
2608 redef class AIntExpr
2611 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2615 redef class AFloatExpr
2618 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2622 redef class ACharExpr
2625 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2629 redef class AArrayExpr
2632 var mtype
= self.mtype
.as(MClassType).arguments
.first
2633 var array
= new Array[RuntimeVariable]
2634 for nexpr
in self.n_exprs
.n_exprs
do
2635 var i
= v
.expr
(nexpr
, mtype
)
2638 return v
.array_instance
(array
, mtype
)
2642 redef class AStringFormExpr
2645 return v
.string_instance
(self.value
.as(not null))
2649 redef class ASuperstringExpr
2652 var array
= new Array[RuntimeVariable]
2653 for ne
in self.n_exprs
do
2654 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2655 var i
= v
.expr
(ne
, null)
2658 var a
= v
.array_instance
(array
, v
.object_type
)
2659 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2664 redef class ACrangeExpr
2667 var i1
= v
.expr
(self.n_expr
, null)
2668 var i2
= v
.expr
(self.n_expr2
, null)
2669 var mtype
= self.mtype
.as(MClassType)
2670 var res
= v
.init_instance
(mtype
)
2671 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2672 v
.check_init_instance
(res
, mtype
)
2677 redef class AOrangeExpr
2680 var i1
= v
.expr
(self.n_expr
, null)
2681 var i2
= v
.expr
(self.n_expr2
, null)
2682 var mtype
= self.mtype
.as(MClassType)
2683 var res
= v
.init_instance
(mtype
)
2684 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2685 v
.check_init_instance
(res
, mtype
)
2690 redef class ATrueExpr
2693 return v
.new_expr
("1", self.mtype
.as(not null))
2697 redef class AFalseExpr
2700 return v
.new_expr
("0", self.mtype
.as(not null))
2704 redef class ANullExpr
2707 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2712 redef class AIsaExpr
2715 var i
= v
.expr
(self.n_expr
, null)
2716 return v
.type_test
(i
, self.cast_type
.as(not null))
2720 redef class AAsCastExpr
2723 var i
= v
.expr
(self.n_expr
, null)
2724 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2726 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2727 v
.add
("if (!{cond}) \{")
2728 v
.add_abort
("Cast failed")
2734 redef class AAsNotnullExpr
2737 var i
= v
.expr
(self.n_expr
, null)
2738 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2740 v
.add
("if ({i} == NULL) \{")
2741 v
.add_abort
("Cast failed")
2747 redef class AParExpr
2750 return v
.expr
(self.n_expr
, null)
2754 redef class AOnceExpr
2757 var mtype
= self.mtype
.as(not null)
2758 var name
= v
.get_name
("varonce")
2759 var guard
= v
.get_name
(name
+ "_guard")
2760 v
.add_decl
("static {mtype.ctype} {name};")
2761 v
.add_decl
("static int {guard};")
2762 var res
= v
.new_var
(mtype
)
2763 v
.add
("if ({guard}) \{")
2764 v
.add
("{res} = {name};")
2766 var i
= v
.expr
(self.n_expr
, mtype
)
2767 v
.add
("{res} = {i};")
2768 v
.add
("{name} = {res};")
2769 v
.add
("{guard} = 1;")
2775 redef class ASendExpr
2778 var recv
= v
.expr
(self.n_expr
, null)
2780 for a
in self.raw_arguments
.as(not null) do
2781 args
.add
(v
.expr
(a
, null))
2783 var mproperty
= self.mproperty
.as(not null)
2784 return v
.send
(mproperty
, args
)
2788 redef class ASendReassignFormExpr
2791 var recv
= v
.expr
(self.n_expr
, null)
2793 for a
in self.raw_arguments
.as(not null) do
2794 args
.add
(v
.expr
(a
, null))
2796 var value
= v
.expr
(self.n_value
, null)
2798 var mproperty
= self.mproperty
.as(not null)
2799 var left
= v
.send
(mproperty
, args
)
2802 var res
= v
.send
(reassign_property
.mproperty
, [left
, value
])
2806 v
.send
(self.write_mproperty
.as(not null), args
)
2810 redef class ASuperExpr
2813 var recv
= v
.frame
.arguments
.first
2815 for a
in self.n_args
.n_exprs
do
2816 args
.add
(v
.expr
(a
, null))
2818 if args
.length
== 1 then
2819 args
= v
.frame
.arguments
2822 var mproperty
= self.mproperty
2823 if mproperty
!= null then
2824 if mproperty
.intro
.msignature
.arity
== 0 then
2828 var res
= v
.send
(mproperty
, args
)
2832 # stantard call-next-method
2833 var mpropdef
= v
.frame
.mpropdef
2834 # FIXME: we do not want an ugly static call!
2835 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2836 if mpropdefs
.length
!= 1 then
2837 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
2838 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2840 mpropdef
= mpropdefs
.first
2841 assert mpropdef
isa MMethodDef
2842 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2847 redef class ANewExpr
2850 var mproperty
= self.mproperty
.as(not null)
2851 var mtype
= self.mtype
.as(MClassType)
2853 var ctype
= mtype
.ctype
2854 if ctype
== "val*" then
2855 recv
= v
.init_instance
(mtype
)
2856 else if ctype
== "void*" then
2857 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2859 debug
("cannot new {mtype}")
2863 for a
in self.n_args
.n_exprs
do
2864 args
.add
(v
.expr
(a
, null))
2866 var res2
= v
.send
(mproperty
, args
)
2867 if res2
!= null then
2868 #self.debug("got {res2} from {mproperty}. drop {recv}")
2871 v
.check_init_instance
(recv
, mtype
)
2876 redef class AAttrExpr
2879 var recv
= v
.expr
(self.n_expr
, null)
2880 var mproperty
= self.mproperty
.as(not null)
2881 return v
.read_attribute
(mproperty
, recv
)
2885 redef class AAttrAssignExpr
2888 var recv
= v
.expr
(self.n_expr
, null)
2889 var i
= v
.expr
(self.n_value
, null)
2890 var mproperty
= self.mproperty
.as(not null)
2891 v
.write_attribute
(mproperty
, recv
, i
)
2895 redef class AAttrReassignExpr
2898 var recv
= v
.expr
(self.n_expr
, null)
2899 var value
= v
.expr
(self.n_value
, null)
2900 var mproperty
= self.mproperty
.as(not null)
2901 var attr
= v
.read_attribute
(mproperty
, recv
)
2902 var res
= v
.send
(reassign_property
.mproperty
, [attr
, value
])
2904 v
.write_attribute
(mproperty
, recv
, res
)
2908 redef class AIssetAttrExpr
2911 var recv
= v
.expr
(self.n_expr
, null)
2912 var mproperty
= self.mproperty
.as(not null)
2913 return v
.isset_attribute
(mproperty
, recv
)
2917 redef class ADebugTypeExpr