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_make_flags
: OptionString = new OptionString("Additional options to make", "--make-flags")
42 var opt_hardening
: OptionBool = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
44 # --no-check-covariance
45 var opt_no_check_covariance
: OptionBool = new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
47 # --no-check-initialization
48 var opt_no_check_initialization
: OptionBool = new OptionBool("Disable isset tests at the end of constructors (dangerous)", "--no-check-initialization")
51 var opt_no_check_assert
: OptionBool = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
54 var opt_no_check_autocast
: OptionBool = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
57 var opt_no_check_other
: OptionBool = new OptionBool("Disable implicit tests: unset attribute, null receiver (dangerous)", "--no-check-other")
62 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_make_flags
, self.opt_hardening
)
63 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
)
67 redef class ModelBuilder
68 # Entry point to performs a global compilation on the AST of a complete program.
69 # `mainmodule` is the main module of the program
70 # `runtime_type_analysis` is a already computer type analysis.
71 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
74 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
76 var compiler
= new GlobalCompiler(mainmodule
, runtime_type_analysis
, self)
77 var v
= compiler
.header
79 for t
in runtime_type_analysis
.live_types
do
80 compiler
.declare_runtimeclass
(v
, t
)
83 compiler
.compile_class_names
85 # Init instance code (allocate and init-arguments)
86 for t
in runtime_type_analysis
.live_types
do
87 if t
.ctype
== "val*" then
88 compiler
.generate_init_instance
(t
)
89 compiler
.generate_check_init_instance
(t
)
91 compiler
.generate_box_instance
(t
)
95 # The main function of the C
96 compiler
.compile_main_function
98 # Compile until all runtime_functions are visited
99 while not compiler
.todos
.is_empty
do
100 var m
= compiler
.todos
.shift
101 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
102 m
.compile_to_c
(compiler
)
104 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
107 self.toolcontext
.info
("*** END VISITING: {time1-time0} ***", 2)
108 write_and_make
(compiler
)
111 protected fun write_and_make
(compiler
: GlobalCompiler)
113 var mainmodule
= compiler
.mainmodule
115 # Generate the .h and .c files
116 # A single C file regroups many compiled rumtime functions
117 # 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
120 var outname
= self.toolcontext
.opt_output
.value
121 if outname
== null then
122 outname
= "{mainmodule.name}.bin"
125 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
126 var h
= new OFStream.open
(hfilename
)
127 for l
in compiler
.header
.decl_lines
do
133 var cfiles
= new Array[String]
135 var file
: nullable OFStream = null
140 for vis
in compiler
.visitors
do
141 count
+= vis
.lines
.length
142 if file
== null or count
> 10000 then
144 if file
!= null then file
.close
145 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
146 cfiles
.add
(cfilename
)
147 file
= new OFStream.open
(cfilename
)
148 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
149 count
= vis
.lines
.length
151 if vis
!= compiler
.header
then
152 for l
in vis
.decl_lines
do
157 for l
in vis
.lines
do
162 if file
!= null then file
.close
164 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
166 # Generate the Makefile
168 var makename
= ".nit_compile/{mainmodule.name}.mk"
169 var makefile
= new OFStream.open
(makename
)
171 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
172 makefile
.write
("all: {outname}\n\n")
174 var ofiles
= new Array[String]
175 # Compile each generated file
177 var o
= f
.strip_extension
(".c") + ".o"
178 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
181 # Compile each required extern body into a specific .o
182 for f
in compiler
.extern_bodies
do
184 var o
= ".nit_compile/{mainmodule.name}.{i}.o"
185 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
189 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
191 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
193 self.toolcontext
.info
("Generated makefile: {makename}", 2)
196 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
198 # Execute the Makefile
200 if self.toolcontext
.opt_no_cc
.value
then return
203 self.toolcontext
.info
("*** COMPILING C ***", 1)
204 var makeflags
= self.toolcontext
.opt_make_flags
.value
205 if makeflags
== null then makeflags
= ""
206 self.toolcontext
.info
("make -B -f {makename} -j 4 {makeflags}", 2)
209 if self.toolcontext
.verbose_level
>= 3 then
210 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1")
212 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
215 toolcontext
.error
(null, "make failed! Error code: {res}.")
219 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
223 # Singleton that store the knowledge about the compilation process
225 # The main module of the program
226 var mainmodule
: MModule writable
228 # The result of the RTA (used to know live types and methods)
229 var runtime_type_analysis
: RapidTypeAnalysis
231 # The modeulbuilder used to know the model and the AST
232 var modelbuilder
: ModelBuilder
234 # Is hardening asked? (see --hardening)
235 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
237 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, modelbuilder
: ModelBuilder)
239 self.header
= new_visitor
240 self.mainmodule
= mainmodule
241 self.runtime_type_analysis
= runtime_type_analysis
242 self.modelbuilder
= modelbuilder
243 self.live_primitive_types
= new Array[MClassType]
244 for t
in runtime_type_analysis
.live_types
do
245 if t
.ctype
!= "val*" then
246 self.live_primitive_types
.add
(t
)
250 # Header declarations
254 protected fun compile_header
do
256 self.header
.add_decl
("#include <stdlib.h>")
257 self.header
.add_decl
("#include <stdio.h>")
258 self.header
.add_decl
("#include <string.h>")
259 self.header
.add_decl
("#ifndef NOBOEHM")
260 self.header
.add_decl
("#include <gc/gc.h>")
261 self.header
.add_decl
("#else /*NOBOEHM*/")
262 self.header
.add_decl
("#define GC_MALLOC(x) calloc(1, (x))")
263 self.header
.add_decl
("#endif /*NOBOEHM*/")
265 compile_header_structs
267 # Global variable used by the legacy native interface
268 self.header
.add_decl
("extern int glob_argc;")
269 self.header
.add_decl
("extern char **glob_argv;")
270 self.header
.add_decl
("extern val *glob_sys;")
273 # Class names (for the class_name and output_class_name methods)
274 protected fun compile_class_names
do
275 self.header
.add_decl
("extern const char const * class_names[];")
276 self.header
.add
("const char const * class_names[] = \{")
277 for t
in self.runtime_type_analysis
.live_types
do
278 self.header
.add
("\"{t}\
", /* {self.classid(t)} */")
280 self.header
.add
("\};")
283 # Declaration of structures the live Nit types
284 # Each live type is generated as an independent C `struct' type.
285 # They only share a common first field `classid` used to implement the polymorphism.
286 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val' that contains only the `classid` field.
287 protected fun compile_header_structs
do
288 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
291 # Subset of runtime_type_analysis.live_types that contains only primitive types
292 # Used to implement the equal test
293 var live_primitive_types
: Array[MClassType]
295 # runtime_functions that need to be compiled
296 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
298 # runtime_functions already seen (todo or done)
299 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
300 fun todo
(m
: AbstractRuntimeFunction)
302 if seen
.has
(m
) then return
307 # Where global declaration are stored (the main .h)
309 # FIXME: should not be a vistor but just somewhere to store lines
310 # FIXME: should not have a global .h since it does not help recompilations
311 var header
: GlobalCompilerVisitor writable
313 # The list of all associated visitors
314 # Used to generate .c files
315 # FIXME: should not be vistors but just somewhere to store lines
316 private var visitors
: List[GlobalCompilerVisitor] = new List[GlobalCompilerVisitor]
318 # List of additional .c files required to compile (native interface)
319 var extern_bodies
= new ArraySet[String]
321 # Return the C symbol associated to a live type runtime
322 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
323 fun classid
(mtype
: MClassType): String
325 if self.classids
.has_key
(mtype
) then
326 return self.classids
[mtype
]
328 print
"No classid for {mtype}"
332 # Cache for classid (computed by declare_runtimeclass)
333 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
335 # Declare C structures and identifiers for a runtime class
336 fun declare_runtimeclass
(v
: GlobalCompilerVisitor, mtype
: MClassType)
338 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
339 v
.add_decl
("/* runtime class {mtype} */")
340 var idnum
= classids
.length
341 var idname
= "ID_" + mtype
.c_name
342 self.classids
[mtype
] = idname
343 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
345 v
.add_decl
("struct {mtype.c_name} \{")
346 v
.add_decl
("int classid; /* must be {idname} */")
348 if mtype
.mclass
.name
== "NativeArray" then
349 # NativeArrays are just a instance header followed by an array of values
350 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
353 if mtype
.ctype
!= "val*" then
354 # Is the Nit type is native then the struct is a box with two fields:
355 # * the `classid` to be polymorph
356 # * the `value` that contains the native value.
357 v
.add_decl
("{mtype.ctype} value;")
360 # Collect all attributes and associate them a field in the structure.
361 # Note: we do not try to optimize the order and helps CC to optimize the client code.
362 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
363 for p
in cd
.intro_mproperties
do
364 if not p
isa MAttribute then continue
365 var t
= p
.intro
.static_mtype
.as(not null)
366 t
= t
.anchor_to
(self.mainmodule
, mtype
)
367 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
373 # Generate the init-instance of a live type (allocate + init-instance)
374 fun generate_init_instance
(mtype
: MClassType)
376 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
377 assert mtype
.ctype
== "val*"
378 var v
= self.new_visitor
380 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
383 if is_native_array
then
389 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
390 v
.add_decl
("/* allocate {mtype} */")
391 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
392 var res
= v
.new_var
(mtype
)
394 if is_native_array
then
395 var mtype_elt
= mtype
.arguments
.first
396 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
398 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
400 v
.add
("{res}->classid = {self.classid(mtype)};")
402 self.generate_init_attr
(v
, res
, mtype
)
403 v
.add
("return {res};")
407 fun generate_check_init_instance
(mtype
: MClassType)
409 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
411 var v
= self.new_visitor
412 var res
= new RuntimeVariable("self", mtype
, mtype
)
413 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
414 v
.add_decl
("/* allocate {mtype} */")
415 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
416 self.generate_check_attr
(v
, res
, mtype
)
420 # Generate code that collect initialize the attributes on a new instance
421 fun generate_init_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
423 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
425 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
426 for npropdef
in n
.n_propdefs
do
427 if npropdef
isa AAttrPropdef then
428 npropdef
.init_expr
(v
, recv
)
434 # Generate a check-init-instance
435 fun generate_check_attr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable, mtype
: MClassType)
437 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
439 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
440 for npropdef
in n
.n_propdefs
do
441 if npropdef
isa AAttrPropdef then
442 npropdef
.check_expr
(v
, recv
)
448 fun generate_box_instance
(mtype
: MClassType)
450 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
451 assert mtype
.ctype
!= "val*"
452 var v
= self.new_visitor
454 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
455 v
.add_decl
("/* allocate {mtype} */")
456 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
457 v
.add
("struct {mtype.c_name}*res = GC_MALLOC(sizeof(struct {mtype.c_name}));")
458 v
.add
("res->classid = {self.classid(mtype)};")
459 v
.add
("res->value = value;")
460 v
.add
("return (val*)res;")
465 # look for a needed .h and .c file for a given .nit source-file
466 # FIXME: bad API, parameter should be a MModule, not its source-file
467 fun add_extern
(file
: String)
469 file
= file
.strip_extension
(".nit")
470 var tryfile
= file
+ ".nit.h"
471 if tryfile
.file_exists
then
472 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
474 tryfile
= file
+ "_nit.h"
475 if tryfile
.file_exists
then
476 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
478 tryfile
= file
+ ".nit.c"
479 if tryfile
.file_exists
then
480 self.extern_bodies
.add
(tryfile
)
482 tryfile
= file
+ "_nit.c"
483 if tryfile
.file_exists
then
484 self.extern_bodies
.add
(tryfile
)
488 # Initialize a visitor specific for a compiler engine
489 fun new_visitor
: GlobalCompilerVisitor do return new GlobalCompilerVisitor(self)
491 # Generate the main C function.
493 # allocate the Sys object if it exists
494 # call init if is exists
495 # call main if it exists
496 fun compile_main_function
498 var v
= self.new_visitor
499 v
.add_decl
("int glob_argc;")
500 v
.add_decl
("char **glob_argv;")
501 v
.add_decl
("val *glob_sys;")
502 v
.add_decl
("int main(int argc, char** argv) \{")
503 v
.add
("glob_argc = argc; glob_argv = argv;")
504 var main_type
= mainmodule
.sys_type
505 if main_type
!= null then
506 var mainmodule
= v
.compiler
.mainmodule
507 var glob_sys
= v
.init_instance
(main_type
)
508 v
.add
("glob_sys = {glob_sys};")
509 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
510 if main_init
!= null then
511 v
.send
(main_init
, [glob_sys
])
513 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
514 if main_method
!= null then
515 v
.send
(main_method
, [glob_sys
])
523 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
527 # Mangle a string to be a unique valid C identifier
528 fun to_cmangle
: String
531 var underscore
= false
533 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
539 res
.append
('_'.ascii
.to_s
)
542 if c
>= '0' and c
<= '9' then
545 else if c
== '_' then
550 res
.append
(c
.ascii
.to_s
)
558 # Escape " \ ' and non printable characters for literal C strings or characters
559 fun escape_to_c
: String
565 else if c
== '\0' then
567 else if c
== '"' then
569 else if c == '\'' then
571 else if c == '\\
' then
573 else if c.ascii < 32 then
574 b.append("\\{c.ascii.to_base(8, false)}")
584 # Return the C type associated to a given Nit static type
590 # Return the name of the C structure associated to a Nit live type
591 # FIXME: move to GlobalCompiler so we can check that self is a live type
592 fun c_name: String is abstract
593 protected var c_name_cache: nullable String protected writable
596 redef class MClassType
599 var res = self.c_name_cache
600 if res != null then return res
601 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
602 self.c_name_cache = res
606 redef fun ctype: String
608 if mclass.name == "Int" then
610 else if mclass.name == "Bool" then
612 else if mclass.name == "Char" then
614 else if mclass.name == "Float" then
616 else if mclass.name == "NativeString" then
618 else if mclass.name == "NativeArray" then
619 #return "{self.arguments.first.ctype}*"
621 else if mclass.kind == extern_kind then
629 redef class MGenericType
632 var res = self.c_name_cache
633 if res != null then return res
635 for t in self.arguments do
638 self.c_name_cache = res
643 # A C function associated to a Nit method
644 # Because of customization, a given Nit method can be compiler more that once
645 abstract class AbstractRuntimeFunction
646 # The associated Nit method
647 var mmethoddef: MMethodDef
649 # The mangled c name of the runtime_function
650 # Subclasses should redefine `build_c_name` instead
653 var res = self.c_name_cache
654 if res != null then return res
655 res = self.build_c_name
656 self.c_name_cache = res
660 # Non cached version of `c_name`
661 protected fun build_c_name: String is abstract
663 private var c_name_cache: nullable String = null
665 # Implements a call of the runtime_function
666 # May inline the body or generate a C function call
667 fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
669 # Generate the code for the RuntimeFunction
670 # Warning: compile more than once compilation makes CC unhappy
671 fun compile_to_c(compiler: GlobalCompiler) is abstract
674 # A runtime function customized on a specific monomrph receiver type
675 private class CustomizedRuntimeFunction
676 super AbstractRuntimeFunction
678 # The considered reciever
679 # (usually is a live type but no strong guarantee)
682 init(mmethoddef: MMethodDef, recv: MClassType)
688 redef fun build_c_name: String
690 var res = self.c_name_cache
691 if res != null then return res
692 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
693 res = self.mmethoddef.c_name
695 res = "{mmethoddef.c_name}__{recv.c_name}"
697 self.c_name_cache = res
702 # used in the compiler worklist
704 if not o isa CustomizedRuntimeFunction then return false
705 if self.mmethoddef != o.mmethoddef then return false
706 if self.recv != o.recv then return false
711 # used in the compiler work-list
713 var res = self.mmethoddef.hash + self.recv.hash
719 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
720 return self.mmethoddef.to_s
722 return "{self.mmethoddef}@{self.recv}"
726 # compile the code customized for the reciever
727 redef fun compile_to_c(compiler)
730 var mmethoddef = self.mmethoddef
731 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
732 print("problem: why do we compile {self} for {recv}?")
736 var v = compiler.new_visitor
737 var selfvar = new RuntimeVariable("self", recv, recv)
738 if compiler.runtime_type_analysis.live_types.has(recv) then
739 selfvar.is_exact = true
741 var arguments = new Array[RuntimeVariable]
742 var frame = new Frame(v, mmethoddef, recv, arguments)
746 var comment = new Buffer
747 var ret = mmethoddef.msignature.return_mtype
749 ret = v.resolve_for(ret, selfvar)
750 sig.append("{ret.ctype} ")
751 else if mmethoddef.mproperty.is_new then
753 sig.append("{ret.ctype} ")
757 sig.append(self.c_name)
758 sig.append("({recv.ctype} {selfvar}")
759 comment.append("(self: {recv}")
760 arguments.add(selfvar)
761 for i in [0..mmethoddef.msignature.arity[ do
762 var mtype = mmethoddef.msignature.mparameters[i].mtype
763 if i == mmethoddef.msignature.vararg_rank then
764 mtype = v.get_class("Array").get_mtype([mtype])
766 mtype = v.resolve_for(mtype, selfvar)
767 comment.append(", {mtype}")
768 sig.append(", {mtype.ctype} p{i}")
769 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
770 arguments.add(argvar)
775 comment.append(": {ret}")
777 compiler.header.add_decl("{sig};")
779 v.add_decl("/* method {self} for {comment} */")
780 v.add_decl("{sig} \{")
781 #v.add("printf(\"method {self} for {comment}\\n\");")
783 frame.returnvar = v.new_var(ret)
785 frame.returnlabel = v.get_name("RET_LABEL")
787 mmethoddef.compile_inside_to_c(v, arguments)
789 v.add("{frame.returnlabel.as(not null)}:;")
791 v.add("return {frame.returnvar.as(not null)};")
796 redef fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
798 var ret = self.mmethoddef.msignature.return_mtype
799 if self.mmethoddef.mproperty.is_new then
803 ret = v.resolve_for(ret, arguments.first)
805 if self.mmethoddef.can_inline(v) then
806 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
807 frame.returnlabel = v.get_name("RET_LABEL")
809 frame.returnvar = v.new_var(ret)
811 var old_frame = v.frame
813 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
814 self.mmethoddef.compile_inside_to_c(v, arguments)
815 v.add("{frame.returnlabel.as(not null)}:(void)0;")
818 return frame.returnvar
820 v.adapt_signature(self.mmethoddef, arguments)
821 v.compiler.todo(self)
823 v.add("{self.c_name}({arguments.join(",")});")
826 var res = v.new_var(ret)
827 v.add("{res} = {self.c_name}({arguments.join(",")});")
833 # A runtime variable hold a runtime value in C.
834 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
836 # 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.
837 class RuntimeVariable
838 # The name of the variable in the C code
841 # The static type of the variable (as declard in C)
844 # The current casted type of the variable (as known in Nit)
845 var mcasttype: MType writable
847 # If the variable exaclty a mcasttype?
848 # false (usual value) means that the variable is a mcasttype or a subtype.
849 var is_exact: Bool writable = false
851 init(name: String, mtype: MType, mcasttype: MType)
855 self.mcasttype = mcasttype
856 assert not mtype.need_anchor
857 assert not mcasttype.need_anchor
860 redef fun to_s do return name
865 if self.is_exact then
871 if self.mtype == self.mcasttype then
872 type_str = "{mtype}{exact_str}"
874 type_str = "{mtype}({mcasttype}{exact_str})"
876 return "<{name}:{type_str}>"
880 # A visitor on the AST of property definition that generate the C code.
881 # Because of inlining, a visitor can visit more than one property.
882 class GlobalCompilerVisitor
883 # The associated compiler
884 var compiler: GlobalCompiler
886 init(compiler: GlobalCompiler)
888 self.compiler = compiler
889 compiler.visitors.add(self)
892 # Alias for self.compiler.mainmodule.object_type
893 fun object_type: MClassType do return self.compiler.mainmodule.object_type
895 # Alias for self.compiler.mainmodule.bool_type
896 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
898 # Force to get the primitive class named `name' or abort
899 fun get_class
(name
: String): MClass
901 return self.compiler
.mainmodule
.get_primitive_class
(name
)
904 # Force to get the primitive property named `name' in the instance `recv' or abort
905 fun get_property
(name
: String, recv
: MType): MMethod
907 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
, self.compiler
.mainmodule
)
911 var frame
: nullable Frame writable
913 # Anchor a type to the main module and the current receiver
914 fun anchor
(mtype
: MType): MType
916 if not mtype
.need_anchor
then return mtype
917 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
918 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
921 # Add a line in the main part of the generated C
928 # (used for local or global declaration)
929 fun add_decl
(s
: String)
931 self.decl_lines
.add
(s
)
934 private var lines
: List[String] = new List[String]
935 private var decl_lines
: List[String] = new List[String]
937 # The current visited AST node
938 var current_node
: nullable ANode = null
940 # Compile an expression an return its result
941 # `mtype` is the expected return type, pass null if no specific type is expected.
942 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
944 var old
= self.current_node
945 self.current_node
= nexpr
946 var res
= nexpr
.expr
(self).as(not null)
947 if mtype
!= null then
948 mtype
= self.anchor
(mtype
)
949 res
= self.autobox
(res
, mtype
)
951 var implicit_cast_to
= nexpr
.implicit_cast_to
952 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
953 var castres
= self.type_test
(res
, implicit_cast_to
)
954 self.add
("if (!{castres}) \{")
955 self.add_abort
("Cast failed")
958 self.current_node
= old
962 # Unsafely cast a value to a new type
963 # ie the result share the same C variable but my have a different mcasttype
964 # NOTE: if the adaptation is useless then `value' is returned as it.
965 # ENSURE: return.name == value.name
966 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
968 mtype
= self.anchor
(mtype
)
969 var valmtype
= value
.mcasttype
970 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
974 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
975 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
978 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
983 # Box or unbox a value to another type iff a C type conversion is needed
984 # ENSURE: result.mtype.ctype == mtype.ctype
985 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
987 if value
.mtype
== mtype
then
989 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
991 else if value
.mtype
.ctype
== "val*" then
992 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
993 else if mtype
.ctype
== "val*" then
994 var valtype
= value
.mtype
.as(MClassType)
995 var res
= self.new_var
(mtype
)
996 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
997 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
998 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
1001 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
1004 # Bad things will appen!
1005 var res
= self.new_var
(mtype
)
1006 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
1007 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
1012 # Correctly assign a left and a right value
1013 # Boxing and unboxing is performed if required
1014 fun assign
(left
, right
: RuntimeVariable)
1016 right
= self.autobox
(right
, left
.mtype
)
1017 self.add
("{left} = {right};")
1021 # Alias for `self.expr(nexpr, self.bool_type)'
1022 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
1024 return expr
(nexpr
, bool_type
)
1027 # Compile a statement (if any)
1028 fun stmt
(nexpr
: nullable AExpr)
1030 if nexpr
== null then return
1031 var old
= self.current_node
1032 self.current_node
= nexpr
1034 self.current_node
= old
1037 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1038 fun debug
(message
: String)
1040 var node
= self.current_node
1041 if node
== null then
1042 print
"?: {message}"
1046 self.add
("/* DEBUG: {message} */")
1049 # Return a new uninitialized local runtime_variable
1050 fun new_var
(mtype
: MType): RuntimeVariable
1052 mtype
= self.anchor
(mtype
)
1053 var name
= self.get_name
("var")
1054 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1055 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1059 # Return a new uninitialized named runtime_variable
1060 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
1062 mtype
= self.anchor
(mtype
)
1063 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1064 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1068 # Return a new local runtime_variable initialized with the C expression `cexpr'.
1069 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
1071 var res
= new_var
(mtype
)
1072 self.add
("{res} = {cexpr};")
1076 # Return the local runtime_variable associated to a Nit local variable
1077 fun variable
(variable
: Variable): RuntimeVariable
1079 if self.variables
.has_key
(variable
) then
1080 return self.variables
[variable
]
1082 var name
= self.get_name
("var_{variable.name}")
1083 var mtype
= variable
.declared_type
.as(not null)
1084 mtype
= self.anchor
(mtype
)
1085 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1086 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1087 self.variables
[variable
] = res
1092 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
1094 # Return an unique and stable identifier associated with an escapemark
1095 fun escapemark_name
(e
: nullable EscapeMark): String
1098 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
1100 if name
== null then name
= "label"
1101 name
= get_name
(name
)
1102 escapemark_names
[e
] = name
1106 private var escapemark_names
= new HashMap[EscapeMark, String]
1108 # Return a new name based on `s' and unique in the visitor
1109 fun get_name
(s
: String): String
1111 if not self.names
.has
(s
) then
1115 var i
= self.last
+ 1
1118 if not self.names
.has
(s2
) then
1127 private var last
: Int = 0
1129 private var names
: HashSet[String] = new HashSet[String]
1131 # Generate a return with the value `s'
1132 fun ret
(s
: RuntimeVariable)
1134 self.assign
(self.frame
.returnvar
.as(not null), s
)
1135 self.add
("goto {self.frame.returnlabel.as(not null)};")
1138 # The runtime types that are acceptable for a given receiver.
1139 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
1141 var mtype
= recv
.mcasttype
1142 if recv
.is_exact
then
1143 assert mtype
isa MClassType
1144 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
1148 var cache
= self.compiler
.collect_types_cache
1149 if cache
.has_key
(mtype
) then
1152 var types
= new Array[MClassType]
1153 var mainmodule
= self.compiler
.mainmodule
1154 for t
in self.compiler
.runtime_type_analysis
.live_types
do
1155 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
1158 cache
[mtype
] = types
1162 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
1164 if not mtype
.need_anchor
then return mtype
1165 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
1166 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
1170 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable])
1172 var elttype
= arguments
.first
.mtype
1173 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
1174 if pname
== "[]" then
1175 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1177 else if pname
== "[]=" then
1178 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1180 else if pname
== "copy_to" then
1181 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
1182 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
1187 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable])
1189 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
1192 # Add a check and an abort for a null reciever is needed
1193 fun check_recv_notnull
(recv
: RuntimeVariable)
1195 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
1197 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
1199 self.add
("if ({recv} == NULL) \{")
1200 self.add_abort
("Reciever is null")
1205 fun compile_callsite
(callsite
: CallSite, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1207 var ret
= self.send
(callsite
.mproperty
, args
)
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
, 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
(mpropdef
: MPropDef, 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])
1402 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
1403 args
.add
(self.vararg_instance
(mpropdef
, recv
, vararg
, elttype
))
1405 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
1406 args
.add
(rawargs
[i
+1])
1409 rawargs
.add_all
(args
)
1413 # Get an instance of a anny for a vararg
1414 fun vararg_instance
(mpropdef
: MPropDef, recv
: RuntimeVariable, varargs
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1416 # FIXME: this is currently buggy since recv is not exact
1418 elttype
= self.resolve_for
(elttype
, recv
)
1419 return self.array_instance
(varargs
, elttype
)
1423 fun bugtype
(recv
: RuntimeVariable)
1425 if recv
.mtype
.ctype
!= "val*" then return
1426 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
1427 self.add
("exit(1);")
1430 # Generate a polymorphic attribute is_set test
1431 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1433 check_recv_notnull
(recv
)
1435 var types
= self.collect_types
(recv
)
1437 var res
= self.new_var
(bool_type
)
1439 if types
.is_empty
then
1440 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1444 self.add
("/* isset {a} on {recv.inspect} */")
1445 self.add
("switch({recv}->classid) \{")
1446 var last
= types
.last
1448 if not self.compiler
.hardening
and t
== last
then
1449 self.add
("default: /*{self.compiler.classid(t)}*/")
1451 self.add
("case {self.compiler.classid(t)}:")
1453 var recv2
= self.autoadapt
(recv
, t
)
1454 var ta
= a
.intro
.static_mtype
.as(not null)
1455 ta
= self.resolve_for
(ta
, recv2
)
1456 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1457 if not ta
isa MNullableType then
1458 if ta
.ctype
== "val*" then
1459 self.add
("{res} = ({attr} != NULL);")
1461 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
1466 if self.compiler
.hardening
then
1467 self.add
("default: /* Bug */")
1475 # Generate a polymorphic attribute read
1476 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1478 check_recv_notnull
(recv
)
1480 var types
= self.collect_types
(recv
)
1482 var ret
= a
.intro
.static_mtype
.as(not null)
1483 ret
= self.resolve_for
(ret
, recv
)
1484 var res
= self.new_var
(ret
)
1486 if types
.is_empty
then
1487 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1491 self.add
("/* read {a} on {recv.inspect} */")
1492 self.add
("switch({recv}->classid) \{")
1493 var last
= types
.last
1495 if not self.compiler
.hardening
and t
== last
then
1496 self.add
("default: /*{self.compiler.classid(t)}*/")
1498 self.add
("case {self.compiler.classid(t)}:")
1500 var recv2
= self.autoadapt
(recv
, t
)
1501 var ta
= a
.intro
.static_mtype
.as(not null)
1502 ta
= self.resolve_for
(ta
, recv2
)
1503 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1504 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
1505 if ta
.ctype
== "val*" then
1506 self.add
("if ({res2} == NULL) \{")
1507 self.add_abort
("Uninitialized attribute {a.name}")
1510 self.add
("/*NOTYET isset on primitive attributes*/")
1513 self.assign
(res
, res2
)
1516 if self.compiler
.hardening
then
1517 self.add
("default: /* Bug */")
1525 # Generate a polymorphic attribute write
1526 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1528 check_recv_notnull
(recv
)
1530 var types
= self.collect_types
(recv
)
1532 if types
.is_empty
then
1533 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1537 self.add
("/* write {a} on {recv.inspect} */")
1538 self.add
("switch({recv}->classid) \{")
1539 var last
= types
.last
1541 if not self.compiler
.hardening
and t
== last
then
1542 self.add
("default: /*{self.compiler.classid(t)}*/")
1544 self.add
("case {self.compiler.classid(t)}:")
1546 var recv2
= self.autoadapt
(recv
, t
)
1547 var ta
= a
.intro
.static_mtype
.as(not null)
1548 ta
= self.resolve_for
(ta
, recv2
)
1549 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1552 if self.compiler
.hardening
then
1553 self.add
("default: /* Bug*/")
1559 # Generate a alloc-instance + init-attributes
1560 fun init_instance
(mtype
: MClassType): RuntimeVariable
1562 mtype
= self.anchor
(mtype
).as(MClassType)
1563 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1564 debug
"problem: {mtype} was detected dead"
1566 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1571 # Generate a polymorphic subtype test
1572 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1574 mtype
= self.anchor
(mtype
)
1575 var mclasstype
= mtype
1576 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
1577 assert mclasstype
isa MClassType
1578 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
1579 debug
"problem: {mtype} was detected cast-dead"
1583 var types
= self.collect_types
(value
)
1585 var res
= self.new_var
(bool_type
)
1587 self.add
("/* isa {mtype} on {value.inspect} */")
1588 if value
.mtype
.ctype
!= "val*" then
1589 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1590 self.add
("{res} = 1;")
1592 self.add
("{res} = 0;")
1596 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
1597 self.add
("if ({value} == NULL) \{")
1598 if mtype
isa MNullableType then
1599 self.add
("{res} = 1; /* isa {mtype} */")
1601 self.add
("{res} = 0; /* not isa {mtype} */")
1603 self.add
("\} else ")
1605 self.add
("switch({value}->classid) \{")
1607 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1608 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1611 self.add
("{res} = 1;")
1613 self.add
("default:")
1614 self.add
("{res} = 0;")
1620 # Generate the code required to dynamically check if 2 objects share the same runtime type
1621 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1623 var res
= self.new_var
(bool_type
)
1624 if value2
.mtype
.ctype
== "val*" then
1625 if value1
.mtype
.ctype
== "val*" then
1626 self.add
"{res} = {value1}->classid == {value2}->classid;"
1628 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
1631 if value1
.mtype
.ctype
== "val*" then
1632 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
1633 else if value1
.mcasttype
== value2
.mcasttype
then
1634 self.add
"{res} = 1;"
1636 self.add
"{res} = 0;"
1642 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1643 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
1644 fun class_name_string
(value
: RuntimeVariable): String
1646 var res
= self.get_name
("var_class_name")
1647 self.add_decl
("const char* {res};")
1648 if value
.mtype
.ctype
== "val*" then
1649 self.add
"{res} = class_names[{value}->classid];"
1651 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
1656 # Generate a Nit "is" for two runtime_variables
1657 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1659 var res
= self.new_var
(bool_type
)
1660 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1665 if value1
.mtype
.ctype
!= "val*" then
1666 if value2
.mtype
== value1
.mtype
then
1667 self.add
("{res} = {value1} == {value2};")
1668 else if value2
.mtype
.ctype
!= "val*" then
1669 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1671 var mtype1
= value1
.mtype
.as(MClassType)
1672 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1673 self.add
("if ({res}) \{")
1674 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1678 var s
= new Array[String]
1679 for t
in self.compiler
.live_primitive_types
do
1680 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1681 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1682 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1685 self.add
("{res} = {value1} == {value2};")
1687 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1693 # Generate a check-init-instance
1694 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType)
1696 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1698 mtype
= self.anchor
(mtype
).as(MClassType)
1699 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1700 debug
"problem: {mtype} was detected dead"
1703 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
1706 # Generate an integer value
1707 fun int_instance
(value
: Int): RuntimeVariable
1709 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1710 self.add
("{res} = {value};")
1714 # Generate an array value
1715 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1717 elttype
= self.anchor
(elttype
)
1718 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
1719 var res
= self.init_instance
(arraytype
)
1720 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1721 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1723 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1724 for i
in [0..array
.length
[ do
1725 var r
= self.autobox
(array
[i
], elttype
)
1726 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1728 var length
= self.int_instance
(array
.length
)
1729 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1730 self.check_init_instance
(res
, arraytype
)
1735 # Generate a string value
1736 fun string_instance
(string
: String): RuntimeVariable
1738 var mtype
= self.get_class
("String").mclass_type
1739 var name
= self.get_name
("varonce")
1740 self.add_decl
("static {mtype.ctype} {name};")
1741 var res
= self.new_var
(mtype
)
1742 self.add
("if ({name}) \{")
1743 self.add
("{res} = {name};")
1744 self.add
("\} else \{")
1745 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1746 self.add
("{nat} = \"{string.escape_to_c}\
";")
1747 var res2
= self.init_instance
(mtype
)
1748 self.add
("{res} = {res2};")
1749 var length
= self.int_instance
(string
.length
)
1750 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
1751 self.check_init_instance
(res
, mtype
)
1752 self.add
("{name} = {res};")
1757 # Generate generic abort
1758 # used by aborts, asserts, casts, etc.
1759 fun add_abort
(message
: String)
1761 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1762 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});")
1764 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
1766 self.add
("exit(1);")
1770 # A frame correspond to a visited property in a GlobalCompilerVisitor
1772 # The associated visitor
1774 var visitor
: GlobalCompilerVisitor
1776 # The executed property.
1777 # A Method in case of a call, an attribute in case of a default initialization.
1778 var mpropdef
: MPropDef
1780 # The static type of the receiver
1781 var receiver
: MClassType
1783 # Arguments of the method (the first is the receiver)
1784 var arguments
: Array[RuntimeVariable]
1786 # The runtime_variable associated to the return (in a function)
1787 var returnvar
: nullable RuntimeVariable writable = null
1789 # The label at the end of the property
1790 var returnlabel
: nullable String writable = null
1793 redef class MPropDef
1794 private var c_name_cache
: nullable String
1796 # The mangled name associated to the property
1799 var res
= self.c_name_cache
1800 if res
!= null then return res
1801 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1802 self.c_name_cache
= res
1807 redef class MMethodDef
1808 # Can the body be inlined?
1809 fun can_inline
(v
: GlobalCompilerVisitor): Bool
1811 var modelbuilder
= v
.compiler
.modelbuilder
1812 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1813 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1814 return npropdef
.can_inline
1815 else if self.mproperty
.name
== "init" then
1816 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1823 # Inline the body in another visitor
1824 fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1826 var modelbuilder
= v
.compiler
.modelbuilder
1827 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1828 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1829 var oldnode
= v
.current_node
1830 v
.current_node
= npropdef
1831 self.compile_parameter_check
(v
, arguments
)
1832 npropdef
.compile_to_c
(v
, self, arguments
)
1833 v
.current_node
= oldnode
1834 else if self.mproperty
.name
== "init" then
1835 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1836 var oldnode
= v
.current_node
1837 v
.current_node
= nclassdef
1838 self.compile_parameter_check
(v
, arguments
)
1839 nclassdef
.compile_to_c
(v
, self, arguments
)
1840 v
.current_node
= oldnode
1847 # Generate type checks in the C code to check covariant parameters
1848 fun compile_parameter_check
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable])
1850 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_covariance
.value
then return
1852 for i
in [0..msignature
.arity
[ do
1853 # skip test for vararg since the array is instantiated with the correct polymorphic type
1854 if msignature
.vararg_rank
== i
then continue
1856 # skip if the cast is not required
1857 var origmtype
= self.mproperty
.intro
.msignature
.mparameters
[i
].mtype
1858 if not origmtype
.need_anchor
then continue
1860 # get the parameter type
1861 var mtype
= self.msignature
.mparameters
[i
].mtype
1864 # note that v decides if and how to implements the cast
1865 v
.add
("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1866 var cond
= v
.type_test
( arguments
[i
+1], mtype
)
1867 v
.add
("if (!{cond}) \{")
1868 #var x = v.class_name_string(arguments[i+1])
1869 #var y = v.class_name_string(arguments.first)
1870 #v.add("fprintf(stderr, \"expected {mtype} (self is %s), got %s for {arguments[i+1].inspect}\\n\", {y}, {x});")
1871 v
.add_abort
("Cast failed")
1877 redef class APropdef
1878 fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1880 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
1881 debug
("Not yet implemented")
1884 fun can_inline
: Bool do return true
1887 redef class AConcreteMethPropdef
1888 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1890 for i
in [0..mpropdef
.msignature
.arity
[ do
1891 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1892 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1894 # Call the implicit super-init
1895 var auto_super_inits
= self.auto_super_inits
1896 if auto_super_inits
!= null then
1897 var selfarg
= [arguments
.first
]
1898 for auto_super_init
in auto_super_inits
do
1899 if auto_super_init
.intro
.msignature
.arity
== 0 then
1900 v
.send
(auto_super_init
, selfarg
)
1902 v
.send
(auto_super_init
, arguments
)
1906 v
.stmt
(self.n_block
)
1909 redef fun can_inline
1911 if self.auto_super_inits
!= null then return false
1912 var nblock
= self.n_block
1913 if nblock
== null then return true
1914 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
1915 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
1920 redef class AInternMethPropdef
1921 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1923 var pname
= mpropdef
.mproperty
.name
1924 var cname
= mpropdef
.mclassdef
.mclass
.name
1925 var ret
= mpropdef
.msignature
.return_mtype
1927 ret
= v
.resolve_for
(ret
, arguments
.first
)
1929 if pname
!= "==" and pname
!= "!=" then
1930 v
.adapt_signature
(mpropdef
, arguments
)
1932 if cname
== "Int" then
1933 if pname
== "output" then
1934 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1936 else if pname
== "object_id" then
1937 v
.ret
(arguments
.first
)
1939 else if pname
== "+" then
1940 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1942 else if pname
== "-" then
1943 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1945 else if pname
== "unary -" then
1946 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1948 else if pname
== "succ" then
1949 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1951 else if pname
== "prec" then
1952 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1954 else if pname
== "*" then
1955 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1957 else if pname
== "/" then
1958 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1960 else if pname
== "%" then
1961 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1963 else if pname
== "lshift" then
1964 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1966 else if pname
== "rshift" then
1967 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1969 else if pname
== "==" then
1970 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1972 else if pname
== "!=" then
1973 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1974 v
.ret
(v
.new_expr
("!{res}", 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
== ">" then
1980 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1982 else if pname
== "<=" then
1983 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1985 else if pname
== ">=" then
1986 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1988 else if pname
== "to_f" then
1989 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1991 else if pname
== "ascii" then
1992 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1995 else if cname
== "Char" then
1996 if pname
== "output" then
1997 v
.add
("printf(\"%c\
", {arguments.first});")
1999 else if pname
== "object_id" then
2000 v
.ret
(arguments
.first
)
2002 else if pname
== "+" then
2003 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2005 else if pname
== "-" then
2006 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2008 else if pname
== "==" then
2009 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2011 else if pname
== "!=" then
2012 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2013 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2015 else if pname
== "succ" then
2016 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2018 else if pname
== "prec" then
2019 v
.ret
(v
.new_expr
("{arguments[0]}-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
== ">" then
2025 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2027 else if pname
== "<=" then
2028 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2030 else if pname
== ">=" then
2031 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2033 else if pname
== "to_i" then
2034 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
2036 else if pname
== "ascii" then
2037 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2040 else if cname
== "Bool" then
2041 if pname
== "output" then
2042 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
2044 else if pname
== "object_id" then
2045 v
.ret
(arguments
.first
)
2047 else if pname
== "==" then
2048 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2050 else if pname
== "!=" then
2051 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2052 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2055 else if cname
== "Float" then
2056 if pname
== "output" then
2057 v
.add
("printf(\"%f\\n\
", {arguments.first});")
2059 else if pname
== "object_id" then
2060 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
2062 else if pname
== "+" then
2063 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2065 else if pname
== "-" then
2066 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2068 else if pname
== "unary -" then
2069 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2071 else if pname
== "succ" then
2072 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2074 else if pname
== "prec" then
2075 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
2077 else if pname
== "*" then
2078 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2080 else if pname
== "/" then
2081 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2083 else if pname
== "==" then
2084 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2086 else if pname
== "!=" then
2087 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2088 v
.ret
(v
.new_expr
("!{res}", 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
== ">" then
2094 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2096 else if pname
== "<=" then
2097 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2099 else if pname
== ">=" then
2100 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2102 else if pname
== "to_i" then
2103 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2106 else if cname
== "Char" then
2107 if pname
== "output" then
2108 v
.add
("printf(\"%c\
", {arguments.first});")
2110 else if pname
== "object_id" then
2111 v
.ret
(arguments
.first
)
2113 else if pname
== "==" then
2114 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2116 else if pname
== "!=" then
2117 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2118 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2120 else if pname
== "ascii" then
2121 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
2124 else if cname
== "NativeString" then
2125 if pname
== "[]" then
2126 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
2128 else if pname
== "[]=" then
2129 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2131 else if pname
== "copy_to" then
2132 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2134 else if pname
== "atoi" then
2135 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
2138 else if cname
== "NativeArray" then
2139 v
.native_array_def
(pname
, ret
, arguments
)
2142 if pname
== "exit" then
2143 v
.add
("exit({arguments[1]});")
2145 else if pname
== "sys" then
2146 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
2148 else if pname
== "calloc_string" then
2149 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
2151 else if pname
== "calloc_array" then
2152 v
.calloc_array
(ret
.as(not null), arguments
)
2154 else if pname
== "object_id" then
2155 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2157 else if pname
== "is_same_type" then
2158 v
.ret
(v
.is_same_type_test
(arguments
[0], arguments
[1]))
2160 else if pname
== "output_class_name" then
2161 var nat
= v
.class_name_string
(arguments
.first
)
2162 v
.add
("printf(\"%s\\n\
", {nat});")
2164 else if pname
== "native_class_name" then
2165 var nat
= v
.class_name_string
(arguments
.first
)
2166 v
.ret
(v
.new_expr
("(char*){nat}", ret
.as(not null)))
2168 else if pname
== "force_garbage_collection" then
2169 v
.add
("GC_gcollect();")
2172 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at
{location.to_s}\\n\
");")
2173 debug
("Not implemented {mpropdef}")
2177 redef class AExternMethPropdef
2178 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2181 var nextern
= self.n_extern
2182 if nextern
== null then
2183 v
.add
("fprintf(stderr, \"NOT YET IMPLEMENTED nitni
for {mpropdef} at
{location.to_s}\\n\
");")
2187 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2188 if location
.file
!= null then
2189 var file
= location
.file
.filename
2190 v
.compiler
.add_extern
(file
)
2192 var res
: nullable RuntimeVariable = null
2193 var ret
= mpropdef
.msignature
.return_mtype
2195 ret
= v
.resolve_for
(ret
, arguments
.first
)
2196 res
= v
.new_var
(ret
)
2198 v
.adapt_signature
(mpropdef
, arguments
)
2201 v
.add
("{externname}({arguments.join(", ")});")
2203 v
.add
("{res} = {externname}({arguments.join(", ")});")
2209 redef class AExternInitPropdef
2210 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2213 var nextern
= self.n_extern
2214 if nextern
== null then
2215 debug
("{mpropdef} need extern name")
2218 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
2219 if location
.file
!= null then
2220 var file
= location
.file
.filename
2221 v
.compiler
.add_extern
(file
)
2223 v
.adapt_signature
(mpropdef
, arguments
)
2224 var ret
= arguments
.first
.mtype
2225 var res
= v
.new_var
(ret
)
2229 v
.add
("{res} = {externname}({arguments.join(", ")});")
2234 redef class AAttrPropdef
2235 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2237 if arguments
.length
== 1 then
2238 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
2239 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
2241 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
2245 fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2247 var nexpr
= self.n_expr
2248 if nexpr
!= null then
2249 var oldnode
= v
.current_node
2250 v
.current_node
= self
2251 var old_frame
= v
.frame
2252 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2254 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
2255 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
2257 v
.current_node
= oldnode
2261 fun check_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
2263 var nexpr
= self.n_expr
2264 if nexpr
!= null then return
2266 var oldnode
= v
.current_node
2267 v
.current_node
= self
2268 var old_frame
= v
.frame
2269 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
2271 # Force read to check the initialization
2272 v
.read_attribute
(self.mpropdef
.mproperty
, recv
)
2274 v
.current_node
= oldnode
2278 redef class AClassdef
2279 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
2281 if mpropdef
== self.mfree_init
then
2282 var super_inits
= self.super_inits
2283 if super_inits
!= null then
2284 assert arguments
.length
== 1
2285 for su
in super_inits
do
2286 v
.send
(su
, arguments
)
2290 var recv
= arguments
.first
2292 # Collect undefined attributes
2293 for npropdef
in self.n_propdefs
do
2294 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
2295 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
2305 redef class ADeferredMethPropdef
2306 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2308 v
.add_abort
("Deferred method called")
2311 redef fun can_inline
do return true
2315 # Try to compile self as an expression
2316 # Do not call this method directly, use `v.expr' instead
2317 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
2319 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
2320 var mtype
= self.mtype
2321 if mtype
== null then
2324 var res
= v
.new_var
(mtype
)
2325 v
.add
("/* {res} = NOT YET {class_name} */")
2330 # Try to compile self as a statement
2331 # Do not call this method directly, use `v.stmt' instead
2332 private fun stmt
(v
: GlobalCompilerVisitor)
2335 if res
!= null then v
.add
("{res};")
2340 redef class ABlockExpr
2343 for e
in self.n_expr
do
2349 redef class AVardeclExpr
2352 var variable
= self.variable
.as(not null)
2353 var ne
= self.n_expr
2355 var i
= v
.expr
(ne
, variable
.declared_type
)
2356 v
.assign
(v
.variable
(variable
), i
)
2361 redef class AVarExpr
2364 var res
= v
.variable
(self.variable
.as(not null))
2365 var mtype
= self.mtype
.as(not null)
2366 return v
.autoadapt
(res
, mtype
)
2370 redef class AVarAssignExpr
2373 var variable
= self.variable
.as(not null)
2374 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
2375 v
.assign
(v
.variable
(variable
), i
)
2379 redef class AVarReassignExpr
2382 var variable
= self.variable
.as(not null)
2383 var vari
= v
.variable
(variable
)
2384 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
2385 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [vari
, value
])
2387 v
.assign
(v
.variable
(variable
), res
)
2391 redef class ASelfExpr
2394 return v
.frame
.arguments
.first
2398 redef class AContinueExpr
2401 v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
2405 redef class ABreakExpr
2408 v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
2412 redef class AReturnExpr
2415 var nexpr
= self.n_expr
2416 if nexpr
!= null then
2417 var returnvar
= v
.frame
.returnvar
.as(not null)
2418 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
2419 v
.assign
(returnvar
, i
)
2421 v
.add
("goto {v.frame.returnlabel.as(not null)};")
2425 redef class AAbortExpr
2428 v
.add_abort
("Aborted")
2435 var cond
= v
.expr_bool
(self.n_expr
)
2436 v
.add
("if ({cond})\{")
2444 redef class AIfexprExpr
2447 var res
= v
.new_var
(self.mtype
.as(not null))
2448 var cond
= v
.expr_bool
(self.n_expr
)
2449 v
.add
("if ({cond})\{")
2450 v
.assign
(res
, v
.expr
(self.n_then
, null))
2452 v
.assign
(res
, v
.expr
(self.n_else
, null))
2461 v
.stmt
(self.n_block
)
2462 var escapemark
= self.escapemark
2463 if escapemark
!= null then
2464 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2469 redef class AWhileExpr
2473 var cond
= v
.expr_bool
(self.n_expr
)
2474 v
.add
("if (!{cond}) break;")
2475 v
.stmt
(self.n_block
)
2476 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2478 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2482 redef class ALoopExpr
2486 v
.stmt
(self.n_block
)
2487 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2489 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2493 redef class AForExpr
2496 var cl
= v
.expr
(self.n_expr
, null)
2497 var it_meth
= self.method_iterator
2498 assert it_meth
!= null
2499 var it
= v
.send
(it_meth
, [cl
])
2502 var isok_meth
= self.method_is_ok
2503 assert isok_meth
!= null
2504 var ok
= v
.send
(isok_meth
, [it
])
2506 v
.add
("if(!{ok}) break;")
2507 if self.variables
.length
== 1 then
2508 var item_meth
= self.method_item
2509 assert item_meth
!= null
2510 var i
= v
.send
(item_meth
, [it
])
2512 v
.assign
(v
.variable
(variables
.first
), i
)
2513 else if self.variables
.length
== 2 then
2514 var key_meth
= self.method_key
2515 assert key_meth
!= null
2516 var i
= v
.send
(key_meth
, [it
])
2518 v
.assign
(v
.variable
(variables
[0]), i
)
2519 var item_meth
= self.method_item
2520 assert item_meth
!= null
2521 i
= v
.send
(item_meth
, [it
])
2523 v
.assign
(v
.variable
(variables
[1]), i
)
2527 v
.stmt
(self.n_block
)
2528 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2529 var next_meth
= self.method_next
2530 assert next_meth
!= null
2531 v
.send
(next_meth
, [it
])
2533 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2537 redef class AAssertExpr
2540 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
2542 var cond
= v
.expr_bool
(self.n_expr
)
2543 v
.add
("if (!{cond}) \{")
2547 v
.add_abort
("Assert '{nid.text}' failed")
2549 v
.add_abort
("Assert failed")
2558 var res
= v
.new_var
(self.mtype
.as(not null))
2559 var i1
= v
.expr_bool
(self.n_expr
)
2560 v
.add
("if ({i1}) \{")
2563 var i2
= v
.expr_bool
(self.n_expr2
)
2564 v
.add
("{res} = {i2};")
2570 redef class AAndExpr
2573 var res
= v
.new_var
(self.mtype
.as(not null))
2574 var i1
= v
.expr_bool
(self.n_expr
)
2575 v
.add
("if (!{i1}) \{")
2578 var i2
= v
.expr_bool
(self.n_expr2
)
2579 v
.add
("{res} = {i2};")
2585 redef class ANotExpr
2588 var cond
= v
.expr_bool
(self.n_expr
)
2589 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2593 redef class AOrElseExpr
2596 var res
= v
.new_var
(self.mtype
.as(not null))
2597 var i1
= v
.expr
(self.n_expr
, null)
2598 v
.add
("if ({i1}!=NULL) \{")
2601 var i2
= v
.expr
(self.n_expr2
, null)
2611 var value1
= v
.expr
(self.n_expr
, null)
2612 var value2
= v
.expr
(self.n_expr2
, null)
2613 return v
.equal_test
(value1
, value2
)
2617 redef class AIntExpr
2620 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2624 redef class AFloatExpr
2627 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2631 redef class ACharExpr
2634 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2638 redef class AArrayExpr
2641 var mtype
= self.mtype
.as(MClassType).arguments
.first
2642 var array
= new Array[RuntimeVariable]
2643 for nexpr
in self.n_exprs
.n_exprs
do
2644 var i
= v
.expr
(nexpr
, mtype
)
2647 return v
.array_instance
(array
, mtype
)
2651 redef class AStringFormExpr
2654 return v
.string_instance
(self.value
.as(not null))
2658 redef class ASuperstringExpr
2661 var array
= new Array[RuntimeVariable]
2662 for ne
in self.n_exprs
do
2663 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2664 var i
= v
.expr
(ne
, null)
2667 var a
= v
.array_instance
(array
, v
.object_type
)
2668 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2673 redef class ACrangeExpr
2676 var i1
= v
.expr
(self.n_expr
, null)
2677 var i2
= v
.expr
(self.n_expr2
, null)
2678 var mtype
= self.mtype
.as(MClassType)
2679 var res
= v
.init_instance
(mtype
)
2680 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2681 v
.check_init_instance
(res
, mtype
)
2686 redef class AOrangeExpr
2689 var i1
= v
.expr
(self.n_expr
, null)
2690 var i2
= v
.expr
(self.n_expr2
, null)
2691 var mtype
= self.mtype
.as(MClassType)
2692 var res
= v
.init_instance
(mtype
)
2693 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2694 v
.check_init_instance
(res
, mtype
)
2699 redef class ATrueExpr
2702 return v
.new_expr
("1", self.mtype
.as(not null))
2706 redef class AFalseExpr
2709 return v
.new_expr
("0", self.mtype
.as(not null))
2713 redef class ANullExpr
2716 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2721 redef class AIsaExpr
2724 var i
= v
.expr
(self.n_expr
, null)
2725 return v
.type_test
(i
, self.cast_type
.as(not null))
2729 redef class AAsCastExpr
2732 var i
= v
.expr
(self.n_expr
, null)
2733 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2735 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2736 v
.add
("if (!{cond}) \{")
2737 v
.add_abort
("Cast failed")
2743 redef class AAsNotnullExpr
2746 var i
= v
.expr
(self.n_expr
, null)
2747 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2749 v
.add
("if ({i} == NULL) \{")
2750 v
.add_abort
("Cast failed")
2756 redef class AParExpr
2759 return v
.expr
(self.n_expr
, null)
2763 redef class AOnceExpr
2766 var mtype
= self.mtype
.as(not null)
2767 var name
= v
.get_name
("varonce")
2768 var guard
= v
.get_name
(name
+ "_guard")
2769 v
.add_decl
("static {mtype.ctype} {name};")
2770 v
.add_decl
("static int {guard};")
2771 var res
= v
.new_var
(mtype
)
2772 v
.add
("if ({guard}) \{")
2773 v
.add
("{res} = {name};")
2775 var i
= v
.expr
(self.n_expr
, mtype
)
2776 v
.add
("{res} = {i};")
2777 v
.add
("{name} = {res};")
2778 v
.add
("{guard} = 1;")
2784 redef class ASendExpr
2787 var recv
= v
.expr
(self.n_expr
, null)
2789 for a
in self.raw_arguments
.as(not null) do
2790 args
.add
(v
.expr
(a
, null))
2792 return v
.compile_callsite
(self.callsite
.as(not null), args
)
2796 redef class ASendReassignFormExpr
2799 var recv
= v
.expr
(self.n_expr
, null)
2801 for a
in self.raw_arguments
.as(not null) do
2802 args
.add
(v
.expr
(a
, null))
2804 var value
= v
.expr
(self.n_value
, null)
2806 var left
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2809 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [left
, value
])
2813 v
.compile_callsite
(self.write_callsite
.as(not null), args
)
2817 redef class ASuperExpr
2820 var recv
= v
.frame
.arguments
.first
2822 for a
in self.n_args
.n_exprs
do
2823 args
.add
(v
.expr
(a
, null))
2825 if args
.length
== 1 then
2826 args
= v
.frame
.arguments
2829 var mproperty
= self.mproperty
2830 if mproperty
!= null then
2831 if mproperty
.intro
.msignature
.arity
== 0 then
2835 var res
= v
.send
(mproperty
, args
)
2839 # stantard call-next-method
2840 var mpropdef
= v
.frame
.mpropdef
2841 # FIXME: we do not want an ugly static call!
2842 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2843 if mpropdefs
.length
!= 1 then
2844 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
2845 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2847 mpropdef
= mpropdefs
.first
2848 assert mpropdef
isa MMethodDef
2849 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2854 redef class ANewExpr
2857 var mtype
= self.mtype
.as(MClassType)
2859 var ctype
= mtype
.ctype
2860 if ctype
== "val*" then
2861 recv
= v
.init_instance
(mtype
)
2862 else if ctype
== "void*" then
2863 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2865 debug
("cannot new {mtype}")
2869 for a
in self.n_args
.n_exprs
do
2870 args
.add
(v
.expr
(a
, null))
2872 var res2
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2873 if res2
!= null then
2874 #self.debug("got {res2} from {mproperty}. drop {recv}")
2877 v
.check_init_instance
(recv
, mtype
)
2882 redef class AAttrExpr
2885 var recv
= v
.expr
(self.n_expr
, null)
2886 var mproperty
= self.mproperty
.as(not null)
2887 return v
.read_attribute
(mproperty
, recv
)
2891 redef class AAttrAssignExpr
2894 var recv
= v
.expr
(self.n_expr
, null)
2895 var i
= v
.expr
(self.n_value
, null)
2896 var mproperty
= self.mproperty
.as(not null)
2897 v
.write_attribute
(mproperty
, recv
, i
)
2901 redef class AAttrReassignExpr
2904 var recv
= v
.expr
(self.n_expr
, null)
2905 var value
= v
.expr
(self.n_value
, null)
2906 var mproperty
= self.mproperty
.as(not null)
2907 var attr
= v
.read_attribute
(mproperty
, recv
)
2908 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [attr
, value
])
2910 v
.write_attribute
(mproperty
, recv
, res
)
2914 redef class AIssetAttrExpr
2917 var recv
= v
.expr
(self.n_expr
, null)
2918 var mproperty
= self.mproperty
.as(not null)
2919 return v
.isset_attribute
(mproperty
, recv
)
2923 redef class ADebugTypeExpr