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.
18 module abstract_compiler
24 private import annotation
27 # Add compiling options
28 redef class ToolContext
30 var opt_output
= new OptionString("Output file", "-o", "--output")
32 var opt_dir
= new OptionString("Output directory", "--dir")
34 var opt_no_cc
= new OptionBool("Do not invoke C compiler", "--no-cc")
36 var opt_no_main
= new OptionBool("Do not generate main entry point", "--no-main")
38 var opt_make_flags
= new OptionString("Additional options to make", "--make-flags")
40 var opt_max_c_lines
= new OptionInt("Maximum number of lines in generated C files. Use 0 for unlimited", 10000, "--max-c-lines")
42 var opt_group_c_files
= new OptionBool("Group all generated code in the same series of files", "--group-c-files")
44 var opt_compile_dir
= new OptionString("Directory used to generate temporary files", "--compile-dir")
46 var opt_hardening
= new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
47 # --no-check-covariance
48 var opt_no_check_covariance
= new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
49 # --no-check-attr-isset
50 var opt_no_check_attr_isset
= new OptionBool("Disable isset tests before each attribute access (dangerous)", "--no-check-attr-isset")
52 var opt_no_check_assert
= new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
54 var opt_no_check_autocast
= new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
56 var opt_no_check_null
= new OptionBool("Disable tests of null receiver (dangerous)", "--no-check-null")
58 var opt_no_check_all
= new OptionBool("Disable all tests (dangerous)", "--no-check-all")
59 # --typing-test-metrics
60 var opt_typing_test_metrics
= new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
61 # --invocation-metrics
62 var opt_invocation_metrics
= new OptionBool("Enable static and dynamic count of all method invocations", "--invocation-metrics")
63 # --isset-checks-metrics
64 var opt_isset_checks_metrics
= new OptionBool("Enable static and dynamic count of isset checks before attributes access", "--isset-checks-metrics")
66 var opt_stacktrace
= new OptionString("Control the generation of stack traces", "--stacktrace")
68 var opt_no_gcc_directive
= new OptionArray("Disable a advanced gcc directives for optimization", "--no-gcc-directive")
70 var opt_release
= new OptionBool("Compile in release mode and finalize application", "--release")
75 self.option_context
.add_option
(self.opt_output
, self.opt_dir
, self.opt_no_cc
, self.opt_no_main
, self.opt_make_flags
, self.opt_compile_dir
, self.opt_hardening
)
76 self.option_context
.add_option
(self.opt_no_check_covariance
, self.opt_no_check_attr_isset
, self.opt_no_check_assert
, self.opt_no_check_autocast
, self.opt_no_check_null
, self.opt_no_check_all
)
77 self.option_context
.add_option
(self.opt_typing_test_metrics
, self.opt_invocation_metrics
, self.opt_isset_checks_metrics
)
78 self.option_context
.add_option
(self.opt_stacktrace
)
79 self.option_context
.add_option
(self.opt_no_gcc_directive
)
80 self.option_context
.add_option
(self.opt_release
)
81 self.option_context
.add_option
(self.opt_max_c_lines
, self.opt_group_c_files
)
83 opt_no_main
.hidden
= true
86 redef fun process_options
(args
)
90 var st
= opt_stacktrace
.value
91 if st
== "none" or st
== "libunwind" or st
== "nitstack" then
93 else if st
== "auto" or st
== null then
95 opt_stacktrace
.value
= "nitstack"
97 print
"Error: unknown value `{st}` for --stacktrace. Use `none`, `libunwind`, `nitstack` or `auto`."
101 if opt_output
.value
!= null and opt_dir
.value
!= null then
102 print
"Error: cannot use both --dir and --output"
106 if opt_no_check_all
.value
then
107 opt_no_check_covariance
.value
= true
108 opt_no_check_attr_isset
.value
= true
109 opt_no_check_assert
.value
= true
110 opt_no_check_autocast
.value
= true
111 opt_no_check_null
.value
= true
116 redef class ModelBuilder
117 # The compilation directory
118 var compile_dir
: String
120 # Simple indirection to `Toolchain::write_and_make`
121 protected fun write_and_make
(compiler
: AbstractCompiler)
123 var platform
= compiler
.mainmodule
.target_platform
125 if platform
== null then
126 toolchain
= new MakefileToolchain(toolcontext
)
128 toolchain
= platform
.toolchain
(toolcontext
)
130 compile_dir
= toolchain
.compile_dir
131 toolchain
.write_and_make compiler
136 fun toolchain
(toolcontext
: ToolContext): Toolchain is abstract
140 var toolcontext
: ToolContext
142 fun compile_dir
: String
144 var compile_dir
= toolcontext
.opt_compile_dir
.value
145 if compile_dir
== null then compile_dir
= ".nit_compile"
149 fun write_and_make
(compiler
: AbstractCompiler) is abstract
152 class MakefileToolchain
155 redef fun write_and_make
(compiler
)
157 var compile_dir
= compile_dir
159 # Generate the .h and .c files
160 # A single C file regroups many compiled rumtime functions
161 # 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
163 self.toolcontext
.info
("*** WRITING C ***", 1)
167 var cfiles
= new Array[String]
168 write_files
(compiler
, compile_dir
, cfiles
)
170 # Generate the Makefile
172 write_makefile
(compiler
, compile_dir
, cfiles
)
175 self.toolcontext
.info
("*** END WRITING C: {time1-time0} ***", 2)
177 # Execute the Makefile
179 if self.toolcontext
.opt_no_cc
.value
then return
182 self.toolcontext
.info
("*** COMPILING C ***", 1)
184 compile_c_code
(compiler
, compile_dir
)
187 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
190 fun write_files
(compiler
: AbstractCompiler, compile_dir
: String, cfiles
: Array[String])
192 var platform
= compiler
.mainmodule
.target_platform
193 if self.toolcontext
.opt_stacktrace
.value
== "nitstack" and (platform
== null or platform
.supports_libunwind
) then compiler
.build_c_to_nit_bindings
194 var cc_opt_with_libgc
= "-DWITH_LIBGC"
195 if platform
!= null and not platform
.supports_libgc
then cc_opt_with_libgc
= ""
197 # Add gc_choser.h to aditionnal bodies
198 var gc_chooser
= new ExternCFile("gc_chooser.c", cc_opt_with_libgc
)
199 if cc_opt_with_libgc
!= "" then gc_chooser
.pkgconfigs
.add
"bdw-gc"
200 compiler
.extern_bodies
.add
(gc_chooser
)
201 var clib
= toolcontext
.nit_dir
/ "clib"
202 compiler
.files_to_copy
.add
"{clib}/gc_chooser.c"
203 compiler
.files_to_copy
.add
"{clib}/gc_chooser.h"
206 for m
in compiler
.mainmodule
.in_importation
.greaters
do
207 compiler
.finalize_ffi_for_module
(m
)
210 # Copy original .[ch] files to compile_dir
211 for src
in compiler
.files_to_copy
do
212 var basename
= src
.basename
("")
213 var dst
= "{compile_dir}/{basename}"
217 var hfilename
= compiler
.header
.file
.name
+ ".h"
218 var hfilepath
= "{compile_dir}/{hfilename}"
219 var h
= new OFStream.open
(hfilepath
)
220 for l
in compiler
.header
.decl_lines
do
224 for l
in compiler
.header
.lines
do
230 var max_c_lines
= toolcontext
.opt_max_c_lines
.value
231 for f
in compiler
.files
do
234 var file
: nullable OFStream = null
235 for vis
in f
.writers
do
236 if vis
== compiler
.header
then continue
237 var total_lines
= vis
.lines
.length
+ vis
.decl_lines
.length
238 if total_lines
== 0 then continue
240 if file
== null or (count
> max_c_lines
and max_c_lines
> 0) then
242 if file
!= null then file
.close
243 var cfilename
= "{f.name}.{i}.c"
244 var cfilepath
= "{compile_dir}/{cfilename}"
245 self.toolcontext
.info
("new C source files to compile: {cfilepath}", 3)
246 cfiles
.add
(cfilename
)
247 file
= new OFStream.open
(cfilepath
)
248 file
.write
"#include \"{f.name}.0.h\
"\n"
251 for l
in vis
.decl_lines
do
255 for l
in vis
.lines
do
260 if file
== null then continue
263 var cfilename
= "{f.name}.0.h"
264 var cfilepath
= "{compile_dir}/{cfilename}"
265 var hfile
: nullable OFStream = null
266 hfile
= new OFStream.open
(cfilepath
)
267 hfile
.write
"#include \"{hfilename}\
"\n"
268 for key
in f
.required_declarations
do
269 if not compiler
.provided_declarations
.has_key
(key
) then
270 var node
= compiler
.requirers_of_declarations
.get_or_null
(key
)
272 node
.debug
"No provided declaration for {key}"
274 print
"No provided declaration for {key}"
278 hfile
.write compiler
.provided_declarations
[key
]
284 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
287 fun makefile_name
(mainmodule
: MModule): String do return "{mainmodule.c_name}.mk"
289 fun default_outname
(mainmodule
: MModule): String
291 # Search a non fictive module
292 var res
= mainmodule
.name
293 while mainmodule
.is_fictive
do
294 mainmodule
= mainmodule
.in_importation
.direct_greaters
.first
295 res
= mainmodule
.name
300 # Combine options and platform informations to get the final path of the outfile
301 fun outfile
(mainmodule
: MModule): String
303 var res
= self.toolcontext
.opt_output
.value
304 if res
!= null then return res
305 res
= default_outname
(mainmodule
)
306 var dir
= self.toolcontext
.opt_dir
.value
307 if dir
!= null then return dir
.join_path
(res
)
311 fun write_makefile
(compiler
: AbstractCompiler, compile_dir
: String, cfiles
: Array[String])
313 var mainmodule
= compiler
.mainmodule
314 var platform
= compiler
.mainmodule
.target_platform
316 var outname
= outfile
(mainmodule
)
318 var real_outpath
= compile_dir
.relpath
(outname
)
319 var outpath
= real_outpath
.escape_to_mk
320 if outpath
!= real_outpath
then
321 # If the name is crazy and need escaping, we will do an indirection
322 # 1. generate the binary in the .nit_compile dir under an escaped name
323 # 2. copy the binary at the right place in the `all` goal.
324 outpath
= mainmodule
.c_name
326 var makename
= makefile_name
(mainmodule
)
327 var makepath
= "{compile_dir}/{makename}"
328 var makefile
= new OFStream.open
(makepath
)
330 var linker_options
= new HashSet[String]
331 for m
in mainmodule
.in_importation
.greaters
do
332 var libs
= m
.collect_linker_libs
333 if libs
!= null then linker_options
.add_all
(libs
)
336 makefile
.write
("CC = ccache cc\nCXX = ccache c++\nCFLAGS = -g -O2 -Wno-unused-value -Wno-switch -Wno-attributes\nCINCL =\nLDFLAGS ?= \nLDLIBS ?= -lm {linker_options.join(" ")}\n\n")
338 var ost
= toolcontext
.opt_stacktrace
.value
339 if (ost
== "libunwind" or ost
== "nitstack") and (platform
== null or platform
.supports_libunwind
) then makefile
.write
("NEED_LIBUNWIND := YesPlease\n")
341 # Dynamic adaptations
342 # While `platform` enable complex toolchains, they are statically applied
343 # For a dynamic adaptsation of the compilation, the generated Makefile should check and adapt things itself
345 # Check and adapt the targeted system
346 makefile
.write
("uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n")
347 makefile
.write
("ifeq ($(uname_S),Darwin)\n")
348 # remove -lunwind since it is already included on macosx
349 makefile
.write
("\tNEED_LIBUNWIND :=\n")
350 makefile
.write
("endif\n\n")
352 # Check and adapt for the compiler used
353 # clang need an additionnal `-Qunused-arguments`
354 makefile
.write
("clang_check := $(shell sh -c '$(CC) -v 2>&1 | grep -q clang; echo $$?')\nifeq ($(clang_check), 0)\n\tCFLAGS += -Qunused-arguments\nendif\n")
356 makefile
.write
("ifdef NEED_LIBUNWIND\n\tLDLIBS += -lunwind\nendif\n")
358 makefile
.write
("all: {outpath}\n")
359 if outpath
!= real_outpath
then
360 makefile
.write
("\tcp -- {outpath.escape_to_sh} {real_outpath.escape_to_sh.replace("$","$$")}")
364 var ofiles
= new Array[String]
365 var dep_rules
= new Array[String]
366 # Compile each generated file
368 var o
= f
.strip_extension
(".c") + ".o"
369 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) $(CINCL) -c -o {o} {f}\n\n")
374 var java_files
= new Array[ExternFile]
376 var pkgconfigs
= new Array[String]
377 for f
in compiler
.extern_bodies
do
378 pkgconfigs
.add_all f
.pkgconfigs
381 if not pkgconfigs
.is_empty
then
383 # does pkg-config exists?
384 ifneq ($(shell which pkg-config >/dev/null; echo $$?), 0)
385 $(error "Command `pkg-config` not found. Please install it")
388 for p
in pkgconfigs
do
390 # Check for library {{{p}}}
391 ifneq ($(shell pkg-config --exists '{{{p}}}'; echo $$?), 0)
392 $(error "pkg-config: package {{{p}}} is not found.")
398 # Compile each required extern body into a specific .o
399 for f
in compiler
.extern_bodies
do
400 var o
= f
.makefile_rule_name
401 var ff
= f
.filename
.basename
("")
402 makefile
.write
("{o}: {ff}\n")
403 makefile
.write
("\t{f.makefile_rule_content}\n\n")
404 dep_rules
.add
(f
.makefile_rule_name
)
406 if f
.compiles_to_o_file
then ofiles
.add
(o
)
407 if f
.add_to_jar
then java_files
.add
(f
)
410 if not java_files
.is_empty
then
411 var jar_file
= "{outpath}.jar"
413 var class_files_array
= new Array[String]
414 for f
in java_files
do class_files_array
.add
(f
.makefile_rule_name
)
415 var class_files
= class_files_array
.join
(" ")
417 makefile
.write
("{jar_file}: {class_files}\n")
418 makefile
.write
("\tjar cf {jar_file} {class_files}\n\n")
419 dep_rules
.add jar_file
424 if not pkgconfigs
.is_empty
then
425 pkg
= "`pkg-config --libs {pkgconfigs.join(" ")}`"
427 makefile
.write
("{outpath}: {dep_rules.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outpath.escape_to_sh} {ofiles.join(" ")} $(LDLIBS) {pkg}\n\n")
429 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n")
430 if outpath
!= real_outpath
then
431 makefile
.write
("\trm -- {outpath.escape_to_sh} 2>/dev/null\n")
434 self.toolcontext
.info
("Generated makefile: {makepath}", 2)
436 makepath
.file_copy_to
"{compile_dir}/Makefile"
439 fun compile_c_code
(compiler
: AbstractCompiler, compile_dir
: String)
441 var makename
= makefile_name
(compiler
.mainmodule
)
443 var makeflags
= self.toolcontext
.opt_make_flags
.value
444 if makeflags
== null then makeflags
= ""
445 self.toolcontext
.info
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags}", 2)
448 if self.toolcontext
.verbose_level
>= 3 then
449 res
= sys
.system
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1")
451 res
= sys
.system
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
454 toolcontext
.error
(null, "make failed! Error code: {res}.")
459 # Singleton that store the knowledge about the compilation process
460 abstract class AbstractCompiler
461 type VISITOR: AbstractCompilerVisitor
463 # Table corresponding c_names to nit names (methods)
464 var names
= new HashMap[String, String]
466 # The main module of the program currently compiled
467 # Is assigned during the separate compilation
468 var mainmodule
: MModule is writable
470 # The real main module of the program
471 var realmainmodule
: MModule is noinit
473 # The modelbuilder used to know the model and the AST
474 var modelbuilder
: ModelBuilder is protected writable
476 # Is hardening asked? (see --hardening)
477 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
481 self.realmainmodule
= mainmodule
484 # Force the creation of a new file
485 # The point is to avoid contamination between must-be-compiled-separately files
486 fun new_file
(name
: String): CodeFile
488 if modelbuilder
.toolcontext
.opt_group_c_files
.value
then
489 if self.files
.is_empty
then
490 var f
= new CodeFile(mainmodule
.c_name
)
493 return self.files
.first
495 var f
= new CodeFile(name
)
500 # The list of all associated files
501 # Used to generate .c files
502 var files
= new List[CodeFile]
504 # Initialize a visitor specific for a compiler engine
505 fun new_visitor
: VISITOR is abstract
507 # Where global declaration are stored (the main .h)
508 var header
: CodeWriter is writable, noinit
510 # Provide a declaration that can be requested (before or latter) by a visitor
511 fun provide_declaration
(key
: String, s
: String)
513 if self.provided_declarations
.has_key
(key
) then
514 assert self.provided_declarations
[key
] == s
516 self.provided_declarations
[key
] = s
519 private var provided_declarations
= new HashMap[String, String]
521 private var requirers_of_declarations
= new HashMap[String, ANode]
523 # Builds the .c and .h files to be used when generating a Stack Trace
524 # Binds the generated C function names to Nit function names
525 fun build_c_to_nit_bindings
527 var compile_dir
= modelbuilder
.compile_dir
529 var stream
= new OFStream.open
("{compile_dir}/c_functions_hash.c")
530 stream
.write
("#include <string.h>\n")
531 stream
.write
("#include <stdlib.h>\n")
532 stream
.write
("#include \"c_functions_hash
.h\
"\n")
533 stream
.write
("typedef struct C_Nit_Names\{char* name; char* nit_name;\}C_Nit_Names;\n")
534 stream
.write
("const char* get_nit_name(register const char* procproc, register unsigned int len)\{\n")
535 stream
.write
("char* procname = malloc(len+1);")
536 stream
.write
("memcpy(procname, procproc, len);")
537 stream
.write
("procname[len] = '\\0';")
538 stream
.write
("static const C_Nit_Names map[{names.length}] = \{\n")
539 for i
in names
.keys
do
541 stream.write(i.escape_to_c)
542 stream.write("\
",\"")
543 stream.write(names[i].escape_to_c)
544 stream.write("\
"\},\n")
546 stream
.write
("\};\n")
547 stream
.write
("int i;")
548 stream
.write
("for(i = 0; i < {names.length}; i++)\{")
549 stream
.write
("if(strcmp(procname,map[i].name) == 0)\{")
550 stream
.write
("free(procname);")
551 stream
.write
("return map[i].nit_name;")
554 stream
.write
("free(procname);")
555 stream
.write
("return NULL;")
559 stream
= new OFStream.open
("{compile_dir}/c_functions_hash.h")
560 stream
.write
("const char* get_nit_name(register const char* procname, register unsigned int len);\n")
563 extern_bodies
.add
(new ExternCFile("{compile_dir}/c_functions_hash.c", ""))
567 # This method call compile_header_strucs method that has to be refined
568 fun compile_header
do
569 self.header
.add_decl
("#include <stdlib.h>")
570 self.header
.add_decl
("#include <stdio.h>")
571 self.header
.add_decl
("#include <string.h>")
572 self.header
.add_decl
("#include \"gc_chooser
.h\
"")
573 self.header
.add_decl
("#ifdef ANDROID")
574 self.header
.add_decl
(" #include <android/log.h>")
575 self.header
.add_decl
(" #define PRINT_ERROR(...) (void)__android_log_print(ANDROID_LOG_WARN, \"Nit\
", __VA_ARGS__)")
576 self.header
.add_decl
("#else")
577 self.header
.add_decl
(" #define PRINT_ERROR(...) fprintf(stderr, __VA_ARGS__)")
578 self.header
.add_decl
("#endif")
580 compile_header_structs
581 compile_nitni_structs
583 var gccd_disable
= modelbuilder
.toolcontext
.opt_no_gcc_directive
.value
584 if gccd_disable
.has
("noreturn") or gccd_disable
.has
("all") then
585 # Signal handler function prototype
586 self.header
.add_decl
("void show_backtrace(int);")
588 self.header
.add_decl
("void show_backtrace(int) __attribute__ ((noreturn));")
591 if gccd_disable
.has
("likely") or gccd_disable
.has
("all") then
592 self.header
.add_decl
("#define likely(x) (x)")
593 self.header
.add_decl
("#define unlikely(x) (x)")
594 else if gccd_disable
.has
("correct-likely") then
595 # invert the `likely` definition
596 # Used by masochists to bench the worst case
597 self.header
.add_decl
("#define likely(x) __builtin_expect((x),0)")
598 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),1)")
600 self.header
.add_decl
("#define likely(x) __builtin_expect((x),1)")
601 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),0)")
604 # Global variable used by intern methods
605 self.header
.add_decl
("extern int glob_argc;")
606 self.header
.add_decl
("extern char **glob_argv;")
607 self.header
.add_decl
("extern val *glob_sys;")
610 # Declaration of structures for live Nit types
611 protected fun compile_header_structs
is abstract
613 # Declaration of structures for nitni undelying the FFI
614 protected fun compile_nitni_structs
616 self.header
.add_decl
"""
617 /* Native reference to Nit objects */
618 /* This structure is used to represent every Nit type in extern methods and custom C code. */
620 struct nitni_ref *next,
621 *prev; /* adjacent global references in global list */
622 int count; /* number of time this global reference has been marked */
625 /* List of global references from C code to Nit objects */
626 /* Instanciated empty at init of Nit system and filled explicitly by user in C code */
627 struct nitni_global_ref_list_t {
628 struct nitni_ref *head, *tail;
630 extern struct nitni_global_ref_list_t *nitni_global_ref_list;
632 /* Initializer of global reference list */
633 extern void nitni_global_ref_list_init();
635 /* Intern function to add a global reference to the list */
636 extern void nitni_global_ref_add( struct nitni_ref *ref );
638 /* Intern function to remove a global reference from the list */
639 extern void nitni_global_ref_remove( struct nitni_ref *ref );
641 /* Increase count on an existing global reference */
642 extern void nitni_global_ref_incr( struct nitni_ref *ref );
644 /* Decrease count on an existing global reference */
645 extern void nitni_global_ref_decr( struct nitni_ref *ref );
649 fun compile_finalizer_function
651 var finalizable_type
= mainmodule
.finalizable_type
652 if finalizable_type
== null then return
654 var finalize_meth
= mainmodule
.try_get_primitive_method
("finalize", finalizable_type
.mclass
)
656 if finalize_meth
== null then
657 modelbuilder
.toolcontext
.error
(null, "The `Finalizable` class doesn't declare the `finalize` method.")
661 var v
= self.new_visitor
662 v
.add_decl
"void gc_finalize (void *obj, void *client_data) \{"
663 var recv
= v
.new_expr
("obj", finalizable_type
)
664 v
.send
(finalize_meth
, [recv
])
668 # Generate the main C function.
672 # * allocate the Sys object if it exists
673 # * call init if is exists
674 # * call main if it exists
675 fun compile_main_function
677 var v
= self.new_visitor
678 v
.add_decl
("#include <signal.h>")
679 var ost
= modelbuilder
.toolcontext
.opt_stacktrace
.value
680 var platform
= mainmodule
.target_platform
682 if platform
!= null and not platform
.supports_libunwind
then ost
= "none"
684 var no_main
= (platform
!= null and platform
.no_main
) or modelbuilder
.toolcontext
.opt_no_main
.value
686 if ost
== "nitstack" or ost
== "libunwind" then
687 v
.add_decl
("#define UNW_LOCAL_ONLY")
688 v
.add_decl
("#include <libunwind.h>")
689 if ost
== "nitstack" then
690 v
.add_decl
("#include \"c_functions_hash
.h\
"")
693 v
.add_decl
("int glob_argc;")
694 v
.add_decl
("char **glob_argv;")
695 v
.add_decl
("val *glob_sys;")
697 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
698 for tag
in count_type_test_tags
do
699 v
.add_decl
("long count_type_test_resolved_{tag};")
700 v
.add_decl
("long count_type_test_unresolved_{tag};")
701 v
.add_decl
("long count_type_test_skipped_{tag};")
702 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
703 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
704 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
708 if self.modelbuilder
.toolcontext
.opt_invocation_metrics
.value
then
709 v
.add_decl
("long count_invoke_by_tables;")
710 v
.add_decl
("long count_invoke_by_direct;")
711 v
.add_decl
("long count_invoke_by_inline;")
712 v
.compiler
.header
.add_decl
("extern long count_invoke_by_tables;")
713 v
.compiler
.header
.add_decl
("extern long count_invoke_by_direct;")
714 v
.compiler
.header
.add_decl
("extern long count_invoke_by_inline;")
717 if self.modelbuilder
.toolcontext
.opt_isset_checks_metrics
.value
then
718 v
.add_decl
("long count_attr_reads = 0;")
719 v
.add_decl
("long count_isset_checks = 0;")
720 v
.compiler
.header
.add_decl
("extern long count_attr_reads;")
721 v
.compiler
.header
.add_decl
("extern long count_isset_checks;")
724 v
.add_decl
("void sig_handler(int signo)\{")
725 v
.add_decl
("PRINT_ERROR(\"Caught signal
: %s\\n\
", strsignal(signo));")
726 v
.add_decl
("show_backtrace(signo);")
729 v
.add_decl
("void show_backtrace (int signo) \{")
730 if ost
== "nitstack" or ost
== "libunwind" then
731 v
.add_decl
("char* opt = getenv(\"NIT_NO_STACK\
");")
732 v
.add_decl
("unw_cursor_t cursor;")
733 v
.add_decl
("if(opt==NULL)\{")
734 v
.add_decl
("unw_context_t uc;")
735 v
.add_decl
("unw_word_t ip;")
736 v
.add_decl
("char* procname = malloc(sizeof(char) * 100);")
737 v
.add_decl
("unw_getcontext(&uc);")
738 v
.add_decl
("unw_init_local(&cursor, &uc);")
739 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
740 v
.add_decl
("PRINT_ERROR(\"-- Stack Trace ------------------------------\\n\
");")
741 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
742 v
.add_decl
("while (unw_step(&cursor) > 0) \{")
743 v
.add_decl
(" unw_get_proc_name(&cursor, procname, 100, &ip);")
744 if ost
== "nitstack" then
745 v
.add_decl
(" const char* recv = get_nit_name(procname, strlen(procname));")
746 v
.add_decl
(" if (recv != NULL)\{")
747 v
.add_decl
(" PRINT_ERROR(\"` %s\\n\", recv);")
748 v.add_decl(" \}else\{")
749 v.add_decl(" PRINT_ERROR(\"` %s\\n\
", procname);")
752 v
.add_decl
(" PRINT_ERROR(\"` %s \\n\",procname);")
755 v.add_decl("PRINT_ERROR(\"-------------------------------------------------\\n\");")
756 v.add_decl("free(procname);")
759 v.add_decl("exit(signo);")
763 v.add_decl("int nit_main(int argc, char** argv) \{")
765 v.add_decl("int main(int argc, char** argv) \{")
768 v.add("signal(SIGABRT, sig_handler);")
769 v.add("signal(SIGFPE, sig_handler);")
770 v.add("signal(SIGILL, sig_handler);")
771 v.add("signal(SIGINT, sig_handler);")
772 v.add("signal(SIGTERM, sig_handler);")
773 v.add("signal(SIGSEGV, sig_handler);")
774 v.add("signal(SIGPIPE, sig_handler);")
776 v.add("glob_argc = argc; glob_argv = argv;")
777 v.add("initialize_gc_option();")
779 v.add "initialize_nitni_global_refs();"
781 var main_type = mainmodule.sys_type
782 if main_type != null then
783 var mainmodule = v.compiler.mainmodule
784 var glob_sys = v.init_instance(main_type)
785 v.add("glob_sys = {glob_sys};")
786 var main_init = mainmodule.try_get_primitive_method("init", main_type.mclass)
787 if main_init != null then
788 v.send(main_init, [glob_sys])
790 var main_method = mainmodule.try_get_primitive_method("run", main_type.mclass) or else
791 mainmodule.try_get_primitive_method("main", main_type.mclass)
792 if main_method != null then
793 v.send(main_method, [glob_sys])
797 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
798 v.add_decl("long count_type_test_resolved_total = 0;")
799 v.add_decl("long count_type_test_unresolved_total = 0;")
800 v.add_decl("long count_type_test_skipped_total = 0;")
801 v.add_decl("long count_type_test_total_total = 0;")
802 for tag in count_type_test_tags do
803 v.add_decl("long count_type_test_total_{tag};")
804 v.add("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
805 v.add("count_type_test_resolved_total += count_type_test_resolved_{tag};")
806 v.add("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
807 v.add("count_type_test_skipped_total += count_type_test_skipped_{tag};")
808 v.add("count_type_test_total_total += count_type_test_total_{tag};")
810 v.add("printf(\"# dynamic count_type_test: total %l\\n\");")
811 v.add("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\");")
812 var tags = count_type_test_tags.to_a
815 v.add("printf(\"{tag}\");")
816 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
817 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
818 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
819 v.add("printf(\"\\t%ld (%.2f%%)\\n\", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
823 if self.modelbuilder.toolcontext.opt_invocation_metrics.value then
824 v.add_decl("long count_invoke_total;")
825 v.add("count_invoke_total = count_invoke_by_tables + count_invoke_by_direct + count_invoke_by_inline;")
826 v.add("printf(\"# dynamic count_invocation: total %ld\\n\", count_invoke_total);")
827 v.add("printf(\"by table: %ld (%.2f%%)\\n\", count_invoke_by_tables, 100.0*count_invoke_by_tables/count_invoke_total);")
828 v.add("printf(\"direct: %ld (%.2f%%)\\n\", count_invoke_by_direct, 100.0*count_invoke_by_direct/count_invoke_total);")
829 v.add("printf(\"inlined: %ld (%.2f%%)\\n\", count_invoke_by_inline, 100.0*count_invoke_by_inline/count_invoke_total);")
832 if self.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
833 v.add("printf(\"# dynamic attribute reads: %ld\\n\", count_attr_reads);")
834 v.add("printf(\"# dynamic isset checks: %ld\\n\", count_isset_checks);")
841 # Copile all C functions related to the [incr|decr]_ref features of the FFI
842 fun compile_nitni_global_ref_functions
844 var v = self.new_visitor
846 struct nitni_global_ref_list_t *nitni_global_ref_list;
847 void initialize_nitni_global_refs() {
848 nitni_global_ref_list = (struct nitni_global_ref_list_t*)nit_alloc(sizeof(struct nitni_global_ref_list_t));
849 nitni_global_ref_list->head = NULL;
850 nitni_global_ref_list->tail = NULL;
853 void nitni_global_ref_add( struct nitni_ref *ref ) {
854 if ( nitni_global_ref_list->head == NULL ) {
855 nitni_global_ref_list->head = ref;
858 nitni_global_ref_list->tail->next = ref;
859 ref->prev = nitni_global_ref_list->tail;
861 nitni_global_ref_list->tail = ref;
866 void nitni_global_ref_remove( struct nitni_ref *ref ) {
867 if ( ref->prev == NULL ) {
868 nitni_global_ref_list->head = ref->next;
870 ref->prev->next = ref->next;
873 if ( ref->next == NULL ) {
874 nitni_global_ref_list->tail = ref->prev;
876 ref->next->prev = ref->prev;
880 extern void nitni_global_ref_incr( struct nitni_ref *ref ) {
881 if ( ref->count == 0 ) /* not registered */
884 nitni_global_ref_add( ref );
890 extern void nitni_global_ref_decr( struct nitni_ref *ref ) {
891 if ( ref->count == 1 ) /* was last reference */
893 /* remove from list */
894 nitni_global_ref_remove( ref );
902 # List of additional files required to compile (FFI)
903 var extern_bodies = new Array[ExternFile]
905 # List of source files to copy over to the compile dir
906 var files_to_copy = new Array[String]
908 # This is used to avoid adding an extern file more than once
909 private var seen_extern = new ArraySet[String]
911 # Generate code that initialize the attributes on a new instance
912 fun generate_init_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
914 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
915 self.mainmodule.linearize_mclassdefs(cds)
917 for npropdef in modelbuilder.collect_attr_propdef(cd) do
918 npropdef.init_expr(v, recv)
923 # Generate code that check if an attribute is correctly initialized
924 fun generate_check_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
926 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
927 self.mainmodule.linearize_mclassdefs(cds)
929 for npropdef in modelbuilder.collect_attr_propdef(cd) do
930 npropdef.check_expr(v, recv)
937 var count_type_test_tags: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
938 var count_type_test_resolved: HashMap[String, Int] = init_count_type_test_tags
939 var count_type_test_unresolved: HashMap[String, Int] = init_count_type_test_tags
940 var count_type_test_skipped: HashMap[String, Int] = init_count_type_test_tags
942 protected fun init_count_type_test_tags: HashMap[String, Int]
944 var res = new HashMap[String, Int]
945 for tag in count_type_test_tags do
951 # Display stats about compilation process
955 # * type tests against resolved types (`x
isa Collection[Animal]`)
956 # * type tests against unresolved types (`x
isa Collection[E
]`)
957 # * type tests skipped
961 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
962 print "# static count_type_test"
963 print "\tresolved:\tunresolved\tskipped\ttotal"
964 var count_type_test_total = init_count_type_test_tags
965 count_type_test_resolved["total"] = 0
966 count_type_test_unresolved["total"] = 0
967 count_type_test_skipped["total"] = 0
968 count_type_test_total["total"] = 0
969 for tag in count_type_test_tags do
970 count_type_test_total[tag] = count_type_test_resolved[tag] + count_type_test_unresolved[tag] + count_type_test_skipped[tag]
971 count_type_test_resolved["total"] += count_type_test_resolved[tag]
972 count_type_test_unresolved["total"] += count_type_test_unresolved[tag]
973 count_type_test_skipped["total"] += count_type_test_skipped[tag]
974 count_type_test_total["total"] += count_type_test_total[tag]
976 var count_type_test = count_type_test_total["total"]
977 var tags = count_type_test_tags.to_a
981 printn "\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
982 printn "\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
983 printn "\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
984 printn "\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
990 fun finalize_ffi_for_module(mmodule: MModule) do mmodule.finalize_ffi(self)
993 # Avoid division by zero by returning the string "n/a"
994 fun div(a,b:Int):String
996 if b == 0 then return "n/a"
997 return ((a*10000/b).to_f / 100.0).to_precision(2)
1001 # A file unit (may be more than one file if
1002 # A file unit aim to be autonomous and is made or one or more `CodeWriter`s
1005 var writers = new Array[CodeWriter]
1006 var required_declarations = new HashSet[String]
1009 # Where to store generated lines
1012 var lines: List[String] = new List[String]
1013 var decl_lines: List[String] = new List[String]
1015 # Add a line in the main part of the generated C
1016 fun add(s: String) do self.lines.add(s)
1019 # (used for local or global declaration)
1020 fun add_decl(s: String) do self.decl_lines.add(s)
1024 file.writers.add(self)
1028 # A visitor on the AST of property definition that generate the C code.
1029 abstract class AbstractCompilerVisitor
1031 type COMPILER: AbstractCompiler
1033 # The associated compiler
1034 var compiler: COMPILER
1036 # The current visited AST node
1037 var current_node: nullable ANode = null is writable
1039 # The current `Frame`
1040 var frame: nullable Frame = null is writable
1042 # Alias for self.compiler.mainmodule.object_type
1043 fun object_type: MClassType do return self.compiler.mainmodule.object_type
1045 # Alias for self.compiler.mainmodule.bool_type
1046 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
1048 var writer: CodeWriter is noinit
1052 self.writer = new CodeWriter(compiler.files.last)
1055 # Force to get the primitive class named `name
` or abort
1056 fun get_class(name: String): MClass do return self.compiler.mainmodule.get_primitive_class(name)
1058 # Force to get the primitive property named `name
` in the instance `recv
` or abort
1059 fun get_property(name: String, recv: MType): MMethod
1061 assert recv isa MClassType
1062 return self.compiler.modelbuilder.force_get_primitive_method(self.current_node, name, recv.mclass, self.compiler.mainmodule)
1065 fun compile_callsite(callsite: CallSite, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1067 var initializers = callsite.mpropdef.initializers
1068 if not initializers.is_empty then
1069 var recv = arguments.first
1072 for p in initializers do
1073 if p isa MMethod then
1075 for x in p.intro.msignature.mparameters do
1076 args.add arguments[i]
1080 else if p isa MAttribute then
1081 self.write_attribute(p, recv, arguments[i])
1085 assert i == arguments.length
1087 return self.send(callsite.mproperty, [recv])
1090 return self.send(callsite.mproperty, arguments)
1093 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable is abstract
1095 fun calloc_array(ret_type: MType, arguments: Array[RuntimeVariable]) is abstract
1097 fun native_array_def(pname: String, ret_type: nullable MType, arguments: Array[RuntimeVariable]) is abstract
1099 # Evaluate `args
` as expressions in the call of `mpropdef
` on `recv
`.
1100 # This method is used to manage varargs in signatures and returns the real array
1101 # of runtime variables to use in the call.
1102 fun varargize(mpropdef: MMethodDef, recv: RuntimeVariable, args: SequenceRead[AExpr]): Array[RuntimeVariable]
1104 var msignature = mpropdef.new_msignature or else mpropdef.msignature.as(not null)
1105 var res = new Array[RuntimeVariable]
1108 if args.is_empty then return res
1110 var vararg_rank = msignature.vararg_rank
1111 var vararg_len = args.length - msignature.arity
1112 if vararg_len < 0 then vararg_len = 0
1114 for i in [0..msignature.arity[ do
1115 if i == vararg_rank then
1117 if ne isa AVarargExpr then
1118 var e = self.expr(ne.n_expr, null)
1122 var vararg = new Array[RuntimeVariable]
1123 for j in [vararg_rank..vararg_rank+vararg_len] do
1124 var e = self.expr(args[j], null)
1127 var elttype = msignature.mparameters[vararg_rank].mtype
1128 var arg = self.vararg_instance(mpropdef, recv, vararg, elttype)
1132 if i > vararg_rank then j += vararg_len
1133 var e = self.expr(args[j], null)
1142 # Anchor a type to the main module and the current receiver
1143 fun anchor(mtype: MType): MType
1145 if not mtype.need_anchor then return mtype
1146 return mtype.anchor_to(self.compiler.mainmodule, self.frame.receiver)
1149 fun resolve_for(mtype: MType, recv: RuntimeVariable): MType
1151 if not mtype.need_anchor then return mtype
1152 return mtype.resolve_for(recv.mcasttype, self.frame.receiver, self.compiler.mainmodule, true)
1155 # Unsafely cast a value to a new type
1156 # ie the result share the same C variable but my have a different mcasttype
1157 # NOTE: if the adaptation is useless then `value
` is returned as it.
1158 # ENSURE: `result
.name
== value
.name
`
1159 fun autoadapt(value: RuntimeVariable, mtype: MType): RuntimeVariable
1161 mtype = self.anchor(mtype)
1162 var valmtype = value.mcasttype
1163 if valmtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1167 if valmtype isa MNullableType and valmtype.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1168 var res = new RuntimeVariable(value.name, valmtype, valmtype.mtype)
1171 var res = new RuntimeVariable(value.name, valmtype, mtype)
1176 # Generate a super call from a method definition
1177 fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1179 # Adapt the arguments of a method according to targetted `MMethodDef`
1180 fun adapt_signature(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1182 # Unbox all the arguments of a method when implemented `extern` or `intern`
1183 fun unbox_signature_extern(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1185 # Box or unbox a value to another type iff a C type conversion is needed
1186 # ENSURE: `result
.mtype
.ctype
== mtype
.ctype
`
1187 fun autobox(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1189 # Box extern classes to be used in the generated code
1190 fun box_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1192 # Unbox extern classes to be used in extern code (legacy NI and FFI)
1193 fun unbox_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1195 # Generate a polymorphic subtype test
1196 fun type_test(value: RuntimeVariable, mtype: MType, tag: String): RuntimeVariable is abstract
1198 # Generate the code required to dynamically check if 2 objects share the same runtime type
1199 fun is_same_type_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1201 # Generate a Nit "is" for two runtime_variables
1202 fun equal_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1206 # Generate a static call on a method definition
1207 fun call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1209 # Generate a polymorphic send for the method `m
` and the arguments `args
`
1210 fun send(m: MMethod, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1212 # Generate a monomorphic send for the method `m
`, the type `t
` and the arguments `args
`
1213 fun monomorphic_send(m: MMethod, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1215 assert t isa MClassType
1216 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
1217 return self.call(propdef, t, args)
1220 # Generate a monomorphic super send from the method `m
`, the type `t
` and the arguments `args
`
1221 fun monomorphic_super_send(m: MMethodDef, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1223 assert t isa MClassType
1224 m = m.lookup_next_definition(self.compiler.mainmodule, t)
1225 return self.call(m, t, args)
1228 # Attributes handling
1230 # Generate a polymorphic attribute is_set test
1231 fun isset_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1233 # Generate a polymorphic attribute read
1234 fun read_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1236 # Generate a polymorphic attribute write
1237 fun write_attribute(a: MAttribute, recv: RuntimeVariable, value: RuntimeVariable) is abstract
1241 # Add a check and an abort for a null receiver if needed
1242 fun check_recv_notnull(recv: RuntimeVariable)
1244 if self.compiler.modelbuilder.toolcontext.opt_no_check_null.value then return
1246 var maybenull = recv.mcasttype isa MNullableType or recv.mcasttype isa MNullType
1248 self.add("if (unlikely({recv} == NULL)) \{")
1249 self.add_abort("Receiver is null")
1256 private var names = new HashSet[String]
1257 private var last: Int = 0
1259 # Return a new name based on `s
` and unique in the visitor
1260 fun get_name(s: String): String
1262 if not self.names.has(s) then
1266 var i = self.last + 1
1269 if not self.names.has(s2) then
1278 # Return an unique and stable identifier associated with an escapemark
1279 fun escapemark_name(e: nullable EscapeMark): String
1282 if frame.escapemark_names.has_key(e) then return frame.escapemark_names[e]
1284 if name == null then name = "label"
1285 name = get_name(name)
1286 frame.escapemark_names[e] = name
1290 # Insert a C label for associated with an escapemark
1291 fun add_escape_label(e: nullable EscapeMark)
1293 if e == null then return
1294 if e.escapes.is_empty then return
1295 add("BREAK_{escapemark_name(e)}: (void)0;")
1298 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1299 # NOTE: we do not return a `RuntimeVariable` "NativeString" as the class may not exist in the module/program
1300 fun class_name_string(value: RuntimeVariable): String is abstract
1302 # Variables handling
1304 protected var variables = new HashMap[Variable, RuntimeVariable]
1306 # Return the local runtime_variable associated to a Nit local variable
1307 fun variable(variable: Variable): RuntimeVariable
1309 if self.variables.has_key(variable) then
1310 return self.variables[variable]
1312 var name = self.get_name("var_{variable.name}")
1313 var mtype = variable.declared_type.as(not null)
1314 mtype = self.anchor(mtype)
1315 var res = new RuntimeVariable(name, mtype, mtype)
1316 self.add_decl("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1317 self.variables[variable] = res
1322 # Return a new uninitialized local runtime_variable
1323 fun new_var(mtype: MType): RuntimeVariable
1325 mtype = self.anchor(mtype)
1326 var name = self.get_name("var")
1327 var res = new RuntimeVariable(name, mtype, mtype)
1328 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1332 # The difference with `new_var
` is the C static type of the local variable
1333 fun new_var_extern(mtype: MType): RuntimeVariable
1335 mtype = self.anchor(mtype)
1336 var name = self.get_name("var")
1337 var res = new RuntimeVariable(name, mtype, mtype)
1338 self.add_decl("{mtype.ctype_extern} {name} /* : {mtype} for extern */;")
1342 # Return a new uninitialized named runtime_variable
1343 fun new_named_var(mtype: MType, name: String): RuntimeVariable
1345 mtype = self.anchor(mtype)
1346 var res = new RuntimeVariable(name, mtype, mtype)
1347 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1351 # Correctly assign a left and a right value
1352 # Boxing and unboxing is performed if required
1353 fun assign(left, right: RuntimeVariable)
1355 right = self.autobox(right, left.mtype)
1356 self.add("{left} = {right};")
1359 # Generate instances
1361 # Generate a alloc-instance + init-attributes
1362 fun init_instance(mtype: MClassType): RuntimeVariable is abstract
1364 # Set a GC finalizer on `recv
`, only if `recv
` isa Finalizable
1365 fun set_finalizer(recv: RuntimeVariable)
1367 var mtype = recv.mtype
1368 var finalizable_type = compiler.mainmodule.finalizable_type
1369 if finalizable_type != null and not mtype.need_anchor and
1370 mtype.is_subtype(compiler.mainmodule, null, finalizable_type) then
1371 add "gc_register_finalizer({recv});"
1375 # Generate an integer value
1376 fun int_instance(value: Int): RuntimeVariable
1378 var res = self.new_var(self.get_class("Int").mclass_type)
1379 self.add("{res} = {value};")
1383 # Generate an integer value
1384 fun bool_instance(value: Bool): RuntimeVariable
1386 var res = self.new_var(self.get_class("Bool").mclass_type)
1388 self.add("{res} = 1;")
1390 self.add("{res} = 0;")
1395 # Generate a string value
1396 fun string_instance(string: String): RuntimeVariable
1398 var mtype = self.get_class("String").mclass_type
1399 var name = self.get_name("varonce")
1400 self.add_decl("static {mtype.ctype} {name};")
1401 var res = self.new_var(mtype)
1402 self.add("if ({name}) \{")
1403 self.add("{res} = {name};")
1404 self.add("\} else \{")
1405 var native_mtype = self.get_class("NativeString").mclass_type
1406 var nat = self.new_var(native_mtype)
1407 self.add("{nat} = \"{string.escape_to_c}\";")
1408 var length = self.int_instance(string.length)
1409 self.add("{res} = {self.send(self.get_property("to_s_with_length", native_mtype), [nat, length]).as(not null)};")
1410 self.add("{name} = {res};")
1415 fun value_instance(object: Object): RuntimeVariable
1417 if object isa Int then
1418 return int_instance(object)
1419 else if object isa Bool then
1420 return bool_instance(object)
1421 else if object isa String then
1422 return string_instance(object)
1428 # Generate an array value
1429 fun array_instance(array: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1431 # Get an instance of a array for a vararg
1432 fun vararg_instance(mpropdef: MPropDef, recv: RuntimeVariable, varargs: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1436 # Add a line in the main part of the generated C
1437 fun add(s: String) do self.writer.lines.add(s)
1440 # (used for local or global declaration)
1441 fun add_decl(s: String) do self.writer.decl_lines.add(s)
1443 # Request the presence of a global declaration
1444 fun require_declaration(key: String)
1446 var reqs = self.writer.file.required_declarations
1447 if reqs.has(key) then return
1449 var node = current_node
1450 if node != null then compiler.requirers_of_declarations[key] = node
1453 # Add a declaration in the local-header
1454 # The declaration is ensured to be present once
1455 fun declare_once(s: String)
1457 self.compiler.provide_declaration(s, s)
1458 self.require_declaration(s)
1461 # look for a needed .h and .c file for a given .nit source-file
1462 # FIXME: bad API, parameter should be a `MModule`, not its source-file
1463 fun add_extern(file: String)
1465 file = file.strip_extension(".nit")
1466 var tryfile = file + ".nit.h"
1467 if tryfile.file_exists then
1468 self.declare_once("#include \"{tryfile.basename("")}\"")
1469 self.compiler.files_to_copy.add(tryfile)
1471 tryfile = file + "_nit.h"
1472 if tryfile.file_exists then
1473 self.declare_once("#include \"{tryfile.basename("")}\"")
1474 self.compiler.files_to_copy.add(tryfile)
1477 if self.compiler.seen_extern.has(file) then return
1478 self.compiler.seen_extern.add(file)
1479 tryfile = file + ".nit.c"
1480 if not tryfile.file_exists then
1481 tryfile = file + "_nit.c"
1482 if not tryfile.file_exists then return
1484 var f = new ExternCFile(tryfile.basename(""), "")
1485 self.compiler.extern_bodies.add(f)
1486 self.compiler.files_to_copy.add(tryfile)
1489 # Return a new local runtime_variable initialized with the C expression `cexpr
`.
1490 fun new_expr(cexpr: String, mtype: MType): RuntimeVariable
1492 var res = new_var(mtype)
1493 self.add("{res} = {cexpr};")
1497 # Generate generic abort
1498 # used by aborts, asserts, casts, etc.
1499 fun add_abort(message: String)
1501 self.add("PRINT_ERROR(\"Runtime error: %s\", \"{message.escape_to_c}\");")
1507 if self.current_node != null and self.current_node.location.file != null then
1508 self.add("PRINT_ERROR(\" (%s:%d)\\n\", \"{self.current_node.location.file.filename.escape_to_c}\", {current_node.location.line_start});")
1510 self.add("PRINT_ERROR(\"\\n\");")
1512 self.add("show_backtrace(1);")
1515 # Add a dynamic cast
1516 fun add_cast(value: RuntimeVariable, mtype: MType, tag: String)
1518 var res = self.type_test(value, mtype, tag)
1519 self.add("if (unlikely(!{res})) \{")
1520 var cn = self.class_name_string(value)
1521 self.add("PRINT_ERROR(\"Runtime error: Cast failed. Expected `%s
`, got `%s
`\", \"{mtype.to_s.escape_to_c}\", {cn});")
1526 # Generate a return with the value `s
`
1527 fun ret(s: RuntimeVariable)
1529 self.assign(self.frame.returnvar.as(not null), s)
1530 self.add("goto {self.frame.returnlabel.as(not null)};")
1533 # Compile a statement (if any)
1534 fun stmt(nexpr: nullable AExpr)
1536 if nexpr == null then return
1538 var narray = nexpr.comprehension
1539 if narray != null then
1540 var recv = frame.comprehension.as(not null)
1541 var val = expr(nexpr, narray.element_mtype)
1542 compile_callsite(narray.push_callsite.as(not null), [recv, val])
1546 var old = self.current_node
1547 self.current_node = nexpr
1549 self.current_node = old
1552 # Compile an expression an return its result
1553 # `mtype
` is the expected return type, pass null if no specific type is expected.
1554 fun expr(nexpr: AExpr, mtype: nullable MType): RuntimeVariable
1556 var old = self.current_node
1557 self.current_node = nexpr
1558 var res = nexpr.expr(self).as(not null)
1559 if mtype != null then
1560 mtype = self.anchor(mtype)
1561 res = self.autobox(res, mtype)
1563 res = autoadapt(res, nexpr.mtype.as(not null))
1564 var implicit_cast_to = nexpr.implicit_cast_to
1565 if implicit_cast_to != null and not self.compiler.modelbuilder.toolcontext.opt_no_check_autocast.value then
1566 add_cast(res, implicit_cast_to, "auto")
1567 res = autoadapt(res, implicit_cast_to)
1569 self.current_node = old
1573 # Alias for `self.expr
(nexpr
, self.bool_type
)`
1574 fun expr_bool(nexpr: AExpr): RuntimeVariable do return expr(nexpr, bool_type)
1576 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1577 fun debug(message: String)
1579 var node = self.current_node
1580 if node == null then
1581 print "?: {message}"
1585 self.add("/* DEBUG: {message} */")
1589 # A C function associated to a Nit method
1590 # Because of customization, a given Nit method can be compiler more that once
1591 abstract class AbstractRuntimeFunction
1593 type COMPILER: AbstractCompiler
1594 type VISITOR: AbstractCompilerVisitor
1596 # The associated Nit method
1597 var mmethoddef: MMethodDef
1599 # The mangled c name of the runtime_function
1600 # Subclasses should redefine `build_c_name
` instead
1603 var res = self.c_name_cache
1604 if res != null then return res
1605 res = self.build_c_name
1606 self.c_name_cache = res
1610 # Non cached version of `c_name
`
1611 protected fun build_c_name: String is abstract
1613 protected var c_name_cache: nullable String = null is writable
1615 # Implements a call of the runtime_function
1616 # May inline the body or generate a C function call
1617 fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1619 # Generate the code for the `AbstractRuntimeFunction`
1620 # Warning: compile more than once compilation makes CC unhappy
1621 fun compile_to_c(compiler: COMPILER) is abstract
1624 # A runtime variable hold a runtime value in C.
1625 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
1627 # 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.
1628 class RuntimeVariable
1629 # The name of the variable in the C code
1632 # The static type of the variable (as declard in C)
1635 # The current casted type of the variable (as known in Nit)
1636 var mcasttype: MType is writable
1638 # If the variable exaclty a mcasttype?
1639 # false (usual value) means that the variable is a mcasttype or a subtype.
1640 var is_exact: Bool = false is writable
1644 assert not mtype.need_anchor
1645 assert not mcasttype.need_anchor
1648 redef fun to_s do return name
1653 if self.is_exact then
1654 exact_str = " exact"
1659 if self.mtype == self.mcasttype then
1660 type_str = "{mtype}{exact_str}"
1662 type_str = "{mtype}({mcasttype}{exact_str})"
1664 return "<{name}:{type_str}>"
1668 # A frame correspond to a visited property in a `GlobalCompilerVisitor`
1671 type VISITOR: AbstractCompilerVisitor
1673 # The associated visitor
1674 var visitor: VISITOR
1676 # The executed property.
1677 # A Method in case of a call, an attribute in case of a default initialization.
1678 var mpropdef: MPropDef
1680 # The static type of the receiver
1681 var receiver: MClassType
1683 # Arguments of the method (the first is the receiver)
1684 var arguments: Array[RuntimeVariable]
1686 # The runtime_variable associated to the return (in a function)
1687 var returnvar: nullable RuntimeVariable = null is writable
1689 # The label at the end of the property
1690 var returnlabel: nullable String = null is writable
1692 # Labels associated to a each escapemarks.
1693 # Because of inlinings, escape-marks must be associated to their context (the frame)
1694 private var escapemark_names = new HashMap[EscapeMark, String]
1696 # The array comprehension currently filled, if any
1697 private var comprehension: nullable RuntimeVariable = null
1701 # Return the C type associated to a given Nit static type
1702 fun ctype: String do return "val*"
1704 # C type outside of the compiler code and in boxes
1705 fun ctype_extern: String do return "val*"
1707 # Short name of the `ctype
` to use in unions
1708 fun ctypename: String do return "val"
1711 redef class MClassType
1713 redef fun ctype: String
1715 if mclass.name == "Int" then
1717 else if mclass.name == "Bool" then
1719 else if mclass.name == "Char" then
1721 else if mclass.name == "Float" then
1723 else if mclass.name == "NativeString" then
1725 else if mclass.name == "NativeArray" then
1732 redef fun ctype_extern: String
1734 if mclass.kind == extern_kind then
1741 redef fun ctypename: String
1743 if mclass.name == "Int" then
1745 else if mclass.name == "Bool" then
1747 else if mclass.name == "Char" then
1749 else if mclass.name == "Float" then
1751 else if mclass.name == "NativeString" then
1753 else if mclass.name == "NativeArray" then
1754 #return "{self.arguments.first.ctype}*"
1762 redef class MPropDef
1763 type VISITOR: AbstractCompilerVisitor
1766 redef class MMethodDef
1767 # Can the body be inlined?
1768 fun can_inline(v: VISITOR): Bool
1770 if is_abstract then return true
1771 var modelbuilder = v.compiler.modelbuilder
1772 var node = modelbuilder.mpropdef2node(self)
1773 if node isa APropdef then
1774 return node.can_inline
1775 else if node isa AClassdef then
1776 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1783 # Inline the body in another visitor
1784 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1786 var modelbuilder = v.compiler.modelbuilder
1787 var val = constant_value
1788 var node = modelbuilder.mpropdef2node(self)
1789 if node isa APropdef then
1790 var oldnode = v.current_node
1791 v.current_node = node
1792 self.compile_parameter_check(v, arguments)
1793 node.compile_to_c(v, self, arguments)
1794 v.current_node = oldnode
1795 else if node isa AClassdef then
1796 var oldnode = v.current_node
1797 v.current_node = node
1798 self.compile_parameter_check(v, arguments)
1799 node.compile_to_c(v, self, arguments)
1800 v.current_node = oldnode
1801 else if val != null then
1802 v.ret(v.value_instance(val))
1809 # Generate type checks in the C code to check covariant parameters
1810 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1812 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1814 for i in [0..msignature.arity[ do
1815 # skip test for vararg since the array is instantiated with the correct polymorphic type
1816 if msignature.vararg_rank == i then continue
1818 # skip if the cast is not required
1819 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1820 if not origmtype.need_anchor then continue
1822 # get the parameter type
1823 var mtype = self.msignature.mparameters[i].mtype
1826 # note that v decides if and how to implements the cast
1827 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1828 v.add_cast(arguments[i+1], mtype, "covariance")
1835 redef class APropdef
1836 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1838 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1839 debug("Not yet implemented")
1842 fun can_inline: Bool do return true
1845 redef class AMethPropdef
1846 redef fun compile_to_c(v, mpropdef, arguments)
1848 if mpropdef.is_abstract then
1849 var cn = v.class_name_string(arguments.first)
1850 v.add("PRINT_ERROR(\"Runtime error: Abstract method `%s
` called on `%s
`\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1855 # Call the implicit super-init
1856 var auto_super_inits = self.auto_super_inits
1857 if auto_super_inits != null then
1858 var args = [arguments.first]
1859 for auto_super_init in auto_super_inits do
1860 assert auto_super_init.mproperty != mpropdef.mproperty
1862 for i in [0..auto_super_init.msignature.arity+1[ do
1863 args.add(arguments[i])
1865 assert auto_super_init.mproperty != mpropdef.mproperty
1866 v.compile_callsite(auto_super_init, args)
1869 if auto_super_call then
1870 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
1873 # Try special compilation
1874 if mpropdef.is_intern then
1875 if compile_intern_to_c(v, mpropdef, arguments) then return
1876 else if mpropdef.is_extern then
1877 if mpropdef.mproperty.is_init then
1878 if compile_externinit_to_c(v, mpropdef, arguments) then return
1880 if compile_externmeth_to_c(v, mpropdef, arguments) then return
1884 # Compile block if any
1885 var n_block = n_block
1886 if n_block != null then
1887 for i in [0..mpropdef.msignature.arity[ do
1888 var variable = self.n_signature.n_params[i].variable.as(not null)
1889 v.assign(v.variable(variable), arguments[i+1])
1896 var cn = v.class_name_string(arguments.first)
1897 v.add("PRINT_ERROR(\"Runtime error: uncompiled method `%s
` called on `%s
`. NOT YET IMPLEMENTED\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1901 redef fun can_inline
1903 if self.auto_super_inits != null then return false
1904 var nblock = self.n_block
1905 if nblock == null then return true
1906 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1907 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1911 fun compile_intern_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
1913 var pname = mpropdef.mproperty.name
1914 var cname = mpropdef.mclassdef.mclass.name
1915 var ret = mpropdef.msignature.return_mtype
1917 ret = v.resolve_for(ret, arguments.first)
1919 if pname != "==" and pname != "!=" then
1920 v.adapt_signature(mpropdef, arguments)
1921 v.unbox_signature_extern(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 == "*" 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 == "%" then
1946 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1948 else if pname == "lshift" then
1949 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1951 else if pname == "rshift" then
1952 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1954 else if pname == "==" then
1955 v.ret(v.equal_test(arguments[0], arguments[1]))
1957 else if pname == "!=" then
1958 var res = v.equal_test(arguments[0], arguments[1])
1959 v.ret(v.new_expr("!{res}", ret.as(not null)))
1961 else if pname == "<" then
1962 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1964 else if pname == ">" then
1965 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1967 else if pname == "<=" then
1968 v.ret(v.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 == "to_f" then
1974 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
1976 else if pname == "ascii" then
1977 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1980 else if cname == "Char" then
1981 if pname == "output" then
1982 v.add("printf(\"%c\", {arguments.first});")
1984 else if pname == "object_id" then
1985 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
1987 else if pname == "successor" then
1988 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1990 else if pname == "predecessor" then
1991 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1993 else if pname == "==" then
1994 v.ret(v.equal_test(arguments[0], arguments[1]))
1996 else if pname == "!=" then
1997 var res = v.equal_test(arguments[0], arguments[1])
1998 v.ret(v.new_expr("!{res}", ret.as(not null)))
2000 else if pname == "<" then
2001 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
2003 else if pname == ">" then
2004 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
2006 else if pname == "<=" then
2007 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
2009 else if pname == ">=" then
2010 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
2012 else if pname == "to_i" then
2013 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
2015 else if pname == "ascii" then
2016 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
2019 else if cname == "Bool" then
2020 if pname == "output" then
2021 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
2023 else if pname == "object_id" then
2024 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2026 else if pname == "==" then
2027 v.ret(v.equal_test(arguments[0], arguments[1]))
2029 else if pname == "!=" then
2030 var res = v.equal_test(arguments[0], arguments[1])
2031 v.ret(v.new_expr("!{res}", ret.as(not null)))
2034 else if cname == "Float" then
2035 if pname == "output" then
2036 v.add("printf(\"%f\\n\", {arguments.first});")
2038 else if pname == "object_id" then
2039 v.ret(v.new_expr("(double){arguments.first}", ret.as(not null)))
2041 else if pname == "+" then
2042 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
2044 else if pname == "-" then
2045 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
2047 else if pname == "unary -" then
2048 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
2050 else if pname == "succ" then
2051 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
2053 else if pname == "prec" then
2054 v.ret(v.new_expr("{arguments[0]}-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 == "/" then
2060 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
2062 else if pname == "==" then
2063 v.ret(v.equal_test(arguments[0], arguments[1]))
2065 else if pname == "!=" then
2066 var res = v.equal_test(arguments[0], arguments[1])
2067 v.ret(v.new_expr("!{res}", ret.as(not null)))
2069 else if pname == "<" then
2070 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
2072 else if pname == ">" then
2073 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
2075 else if pname == "<=" then
2076 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
2078 else if pname == ">=" then
2079 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
2081 else if pname == "to_i" then
2082 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
2085 else if cname == "NativeString" then
2086 if pname == "[]" then
2087 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
2089 else if pname == "[]=" then
2090 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2092 else if pname == "copy_to" then
2093 v.add("memmove({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2095 else if pname == "atoi" then
2096 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
2098 else if pname == "new" then
2099 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2102 else if cname == "NativeArray" then
2103 v.native_array_def(pname, ret, arguments)
2106 if pname == "exit" then
2107 v.add("exit({arguments[1]});")
2109 else if pname == "sys" then
2110 v.ret(v.new_expr("glob_sys", ret.as(not null)))
2112 else if pname == "calloc_string" then
2113 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2115 else if pname == "calloc_array" then
2116 v.calloc_array(ret.as(not null), arguments)
2118 else if pname == "object_id" then
2119 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2121 else if pname == "is_same_type" then
2122 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
2124 else if pname == "is_same_instance" then
2125 v.ret(v.equal_test(arguments[0], arguments[1]))
2127 else if pname == "output_class_name" then
2128 var nat = v.class_name_string(arguments.first)
2129 v.add("printf(\"%s\\n\", {nat});")
2131 else if pname == "native_class_name" then
2132 var nat = v.class_name_string(arguments.first)
2133 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
2135 else if pname == "force_garbage_collection" then
2136 v.add("nit_gcollect();")
2138 else if pname == "native_argc" then
2139 v.ret(v.new_expr("glob_argc", ret.as(not null)))
2141 else if pname == "native_argv" then
2142 v.ret(v.new_expr("glob_argv[{arguments[1]}]", ret.as(not null)))
2148 # Compile an extern method
2149 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2150 fun compile_externmeth_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
2153 var at = self.get_single_annotation("extern", v.compiler.modelbuilder)
2155 externname = at.arg_as_string(v.compiler.modelbuilder)
2156 if externname == null then return false
2160 if location.file != null then
2161 var file = location.file.filename
2164 var res: nullable RuntimeVariable = null
2165 var ret = mpropdef.msignature.return_mtype
2167 ret = v.resolve_for(ret, arguments.first)
2168 res = v.new_var_extern(ret)
2170 v.adapt_signature(mpropdef, arguments)
2171 v.unbox_signature_extern(mpropdef, arguments)
2174 v.add("{externname}({arguments.join(", ")});")
2176 v.add("{res} = {externname}({arguments.join(", ")});")
2177 res = v.box_extern(res, ret.as(not null))
2183 # Compile an extern factory
2184 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2185 fun compile_externinit_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
2188 var at = self.get_single_annotation("extern", v.compiler.modelbuilder)
2190 externname = at.arg_as_string(v.compiler.modelbuilder)
2191 if externname == null then return false
2195 if location.file != null then
2196 var file = location.file.filename
2199 v.adapt_signature(mpropdef, arguments)
2200 v.unbox_signature_extern(mpropdef, arguments)
2201 var ret = arguments.first.mtype
2202 var res = v.new_var_extern(ret)
2206 v.add("{res} = {externname}({arguments.join(", ")});")
2207 res = v.box_extern(res, ret)
2213 redef class AAttrPropdef
2214 redef fun can_inline: Bool do return not is_lazy
2216 redef fun compile_to_c(v, mpropdef, arguments)
2218 if mpropdef == mreadpropdef then
2219 assert arguments.length == 1
2220 var recv = arguments.first
2224 var ret = self.mpropdef.static_mtype
2225 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2226 var guard = self.mlazypropdef.mproperty
2228 set = v.isset_attribute(self.mpropdef.mproperty, recv)
2230 set = v.read_attribute(guard, recv)
2232 v.add("if(likely({set})) \{")
2233 res = v.read_attribute(self.mpropdef.mproperty, recv)
2236 var value = evaluate_expr(v, recv)
2238 v.assign(res, value)
2240 var true_v = v.new_expr("1", v.bool_type)
2241 v.write_attribute(guard, arguments.first, true_v)
2245 res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
2247 v.assign(v.frame.returnvar.as(not null), res)
2248 else if mpropdef == mwritepropdef then
2249 assert arguments.length == 2
2250 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
2252 var ret = self.mpropdef.static_mtype
2253 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2255 v.write_attribute(self.mlazypropdef.mproperty, arguments.first, v.new_expr("1", v.bool_type))
2263 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2265 if has_value and not is_lazy then evaluate_expr(v, recv)
2268 # Evaluate, store and return the default value of the attribute
2269 private fun evaluate_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable): RuntimeVariable
2271 var oldnode = v.current_node
2272 v.current_node = self
2273 var old_frame = v.frame
2274 var frame = new Frame(v, self.mpropdef.as(not null), recv.mcasttype.as_notnullable.as(MClassType), [recv])
2278 var mtype = self.mpropdef.static_mtype
2279 assert mtype != null
2281 var nexpr = self.n_expr
2282 var nblock = self.n_block
2283 if nexpr != null then
2284 value = v.expr(nexpr, mtype)
2285 else if nblock != null then
2286 value = v.new_var(mtype)
2287 frame.returnvar = value
2288 frame.returnlabel = v.get_name("RET_LABEL")
2291 v.add("{frame.returnlabel.as(not null)}:(void)0;")
2297 v.write_attribute(self.mpropdef.mproperty, recv, value)
2300 v.current_node = oldnode
2305 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2307 var nexpr = self.n_expr
2308 if nexpr != null then return
2310 var oldnode = v.current_node
2311 v.current_node = self
2312 var old_frame = v.frame
2313 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
2315 # Force read to check the initialization
2316 v.read_attribute(self.mpropdef.mproperty, recv)
2318 v.current_node = oldnode
2322 redef class AClassdef
2323 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
2325 if mpropdef == self.mfree_init then
2326 assert mpropdef.mproperty.is_root_init
2327 assert arguments.length == 1
2328 if not mpropdef.is_intro then
2329 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
2339 # Try to compile self as an expression
2340 # Do not call this method directly, use `v
.expr
` instead
2341 private fun expr(v: AbstractCompilerVisitor): nullable RuntimeVariable
2343 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\");")
2344 var mtype = self.mtype
2345 if mtype == null then
2348 var res = v.new_var(mtype)
2349 v.add("/* {res} = NOT YET {class_name} */")
2354 # Try to compile self as a statement
2355 # Do not call this method directly, use `v
.stmt
` instead
2356 private fun stmt(v: AbstractCompilerVisitor)
2362 redef class ABlockExpr
2365 for e in self.n_expr do v.stmt(e)
2369 var last = self.n_expr.last
2370 for e in self.n_expr do
2371 if e == last then break
2374 return v.expr(last, null)
2378 redef class AVardeclExpr
2381 var variable = self.variable.as(not null)
2382 var ne = self.n_expr
2384 var i = v.expr(ne, variable.declared_type)
2385 v.assign(v.variable(variable), i)
2390 redef class AVarExpr
2393 var res = v.variable(self.variable.as(not null))
2394 var mtype = self.mtype.as(not null)
2395 return v.autoadapt(res, mtype)
2399 redef class AVarAssignExpr
2402 var variable = self.variable.as(not null)
2403 var i = v.expr(self.n_value, variable.declared_type)
2404 v.assign(v.variable(variable), i)
2409 redef class AVarReassignExpr
2412 var variable = self.variable.as(not null)
2413 var vari = v.variable(variable)
2414 var value = v.expr(self.n_value, variable.declared_type)
2415 var res = v.compile_callsite(self.reassign_callsite.as(not null), [vari, value])
2417 v.assign(v.variable(variable), res)
2421 redef class ASelfExpr
2422 redef fun expr(v) do return v.frame.arguments.first
2425 redef class AEscapeExpr
2426 redef fun stmt(v) do v.add("goto BREAK_{v.escapemark_name(self.escapemark)};")
2429 redef class AReturnExpr
2432 var nexpr = self.n_expr
2433 if nexpr != null then
2434 var returnvar = v.frame.returnvar.as(not null)
2435 var i = v.expr(nexpr, returnvar.mtype)
2436 v.assign(returnvar, i)
2438 v.add("goto {v.frame.returnlabel.as(not null)};")
2442 redef class AAbortExpr
2443 redef fun stmt(v) do v.add_abort("Aborted")
2449 var cond = v.expr_bool(self.n_expr)
2450 v.add("if ({cond})\{")
2459 var res = v.new_var(self.mtype.as(not null))
2460 var cond = v.expr_bool(self.n_expr)
2461 v.add("if ({cond})\{")
2462 v.assign(res, v.expr(self.n_then.as(not null), null))
2464 v.assign(res, v.expr(self.n_else.as(not null), null))
2470 redef class AIfexprExpr
2473 var res = v.new_var(self.mtype.as(not null))
2474 var cond = v.expr_bool(self.n_expr)
2475 v.add("if ({cond})\{")
2476 v.assign(res, v.expr(self.n_then, null))
2478 v.assign(res, v.expr(self.n_else, null))
2487 v.stmt(self.n_block)
2488 v.add_escape_label(break_mark)
2492 redef class AWhileExpr
2496 var cond = v.expr_bool(self.n_expr)
2497 v.add("if (!{cond}) break;")
2498 v.stmt(self.n_block)
2499 v.add_escape_label(continue_mark)
2501 v.add_escape_label(break_mark)
2505 redef class ALoopExpr
2509 v.stmt(self.n_block)
2510 v.add_escape_label(continue_mark)
2512 v.add_escape_label(break_mark)
2516 redef class AForExpr
2519 var cl = v.expr(self.n_expr, null)
2520 var it_meth = self.method_iterator
2521 assert it_meth != null
2522 var it = v.compile_callsite(it_meth, [cl])
2525 var isok_meth = self.method_is_ok
2526 assert isok_meth != null
2527 var ok = v.compile_callsite(isok_meth, [it])
2529 v.add("if(!{ok}) break;")
2530 if self.variables.length == 1 then
2531 var item_meth = self.method_item
2532 assert item_meth != null
2533 var i = v.compile_callsite(item_meth, [it])
2535 v.assign(v.variable(variables.first), i)
2536 else if self.variables.length == 2 then
2537 var key_meth = self.method_key
2538 assert key_meth != null
2539 var i = v.compile_callsite(key_meth, [it])
2541 v.assign(v.variable(variables[0]), i)
2542 var item_meth = self.method_item
2543 assert item_meth != null
2544 i = v.compile_callsite(item_meth, [it])
2546 v.assign(v.variable(variables[1]), i)
2550 v.stmt(self.n_block)
2551 v.add_escape_label(continue_mark)
2552 var next_meth = self.method_next
2553 assert next_meth != null
2554 v.compile_callsite(next_meth, [it])
2556 v.add_escape_label(break_mark)
2558 var method_finish = self.method_finish
2559 if method_finish != null then
2560 # TODO: Find a way to call this also in long escape (e.g. return)
2561 v.compile_callsite(method_finish, [it])
2566 redef class AAssertExpr
2569 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return
2571 var cond = v.expr_bool(self.n_expr)
2572 v.add("if (unlikely(!{cond})) \{")
2576 v.add_abort("Assert '{nid.text}' failed")
2578 v.add_abort("Assert failed")
2587 var res = v.new_var(self.mtype.as(not null))
2588 var i1 = v.expr_bool(self.n_expr)
2589 v.add("if ({i1}) \{")
2592 var i2 = v.expr_bool(self.n_expr2)
2593 v.add("{res} = {i2};")
2599 redef class AImpliesExpr
2602 var res = v.new_var(self.mtype.as(not null))
2603 var i1 = v.expr_bool(self.n_expr)
2604 v.add("if (!{i1}) \{")
2607 var i2 = v.expr_bool(self.n_expr2)
2608 v.add("{res} = {i2};")
2614 redef class AAndExpr
2617 var res = v.new_var(self.mtype.as(not null))
2618 var i1 = v.expr_bool(self.n_expr)
2619 v.add("if (!{i1}) \{")
2622 var i2 = v.expr_bool(self.n_expr2)
2623 v.add("{res} = {i2};")
2629 redef class ANotExpr
2632 var cond = v.expr_bool(self.n_expr)
2633 return v.new_expr("!{cond}", self.mtype.as(not null))
2637 redef class AOrElseExpr
2640 var res = v.new_var(self.mtype.as(not null))
2641 var i1 = v.expr(self.n_expr, null)
2642 v.add("if ({i1}!=NULL) \{")
2645 var i2 = v.expr(self.n_expr2, null)
2652 redef class AIntExpr
2653 redef fun expr(v) do return v.new_expr("{self.value.to_s}", self.mtype.as(not null))
2656 redef class AFloatExpr
2657 redef fun expr(v) do return v.new_expr("{self.n_float.text}", self.mtype.as(not null)) # FIXME use value, not n_float
2660 redef class ACharExpr
2661 redef fun expr(v) do return v.new_expr("'{self.value.to_s.escape_to_c}'", self.mtype.as(not null))
2664 redef class AArrayExpr
2667 var mtype = self.element_mtype.as(not null)
2668 var array = new Array[RuntimeVariable]
2669 var res = v.array_instance(array, mtype)
2671 var old_comprehension = v.frame.comprehension
2672 v.frame.comprehension = res
2673 for nexpr in self.n_exprs do
2676 v.frame.comprehension = old_comprehension
2682 redef class AStringFormExpr
2683 redef fun expr(v) do return v.string_instance(self.value.as(not null))
2686 redef class ASuperstringExpr
2689 var array = new Array[RuntimeVariable]
2690 for ne in self.n_exprs do
2691 if ne isa AStringFormExpr and ne.value == "" then continue # skip empty sub-strings
2692 var i = v.expr(ne, null)
2695 var a = v.array_instance(array, v.object_type)
2696 var res = v.send(v.get_property("to_s", a.mtype), [a])
2701 redef class ACrangeExpr
2704 var i1 = v.expr(self.n_expr, null)
2705 var i2 = v.expr(self.n_expr2, null)
2706 var mtype = self.mtype.as(MClassType)
2707 var res = v.init_instance(mtype)
2708 v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2713 redef class AOrangeExpr
2716 var i1 = v.expr(self.n_expr, null)
2717 var i2 = v.expr(self.n_expr2, null)
2718 var mtype = self.mtype.as(MClassType)
2719 var res = v.init_instance(mtype)
2720 v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2725 redef class ATrueExpr
2726 redef fun expr(v) do return v.new_expr("1", self.mtype.as(not null))
2729 redef class AFalseExpr
2730 redef fun expr(v) do return v.new_expr("0", self.mtype.as(not null))
2733 redef class ANullExpr
2734 redef fun expr(v) do return v.new_expr("NULL", self.mtype.as(not null))
2737 redef class AIsaExpr
2740 var i = v.expr(self.n_expr, null)
2741 return v.type_test(i, self.cast_type.as(not null), "isa")
2745 redef class AAsCastExpr
2748 var i = v.expr(self.n_expr, null)
2749 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2751 v.add_cast(i, self.mtype.as(not null), "as")
2756 redef class AAsNotnullExpr
2759 var i = v.expr(self.n_expr, null)
2760 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2762 if i.mtype.ctype != "val*" then return i
2764 v.add("if (unlikely({i} == NULL)) \{")
2765 v.add_abort("Cast failed")
2771 redef class AParExpr
2772 redef fun expr(v) do return v.expr(self.n_expr, null)
2775 redef class AOnceExpr
2778 var mtype = self.mtype.as(not null)
2779 var name = v.get_name("varonce")
2780 var guard = v.get_name(name + "_guard")
2781 v.add_decl("static {mtype.ctype} {name};")
2782 v.add_decl("static int {guard};")
2783 var res = v.new_var(mtype)
2784 v.add("if ({guard}) \{")
2785 v.add("{res} = {name};")
2787 var i = v.expr(self.n_expr, mtype)
2788 v.add("{res} = {i};")
2789 v.add("{name} = {res};")
2790 v.add("{guard} = 1;")
2796 redef class ASendExpr
2799 var recv = v.expr(self.n_expr, null)
2800 var callsite = self.callsite.as(not null)
2801 var args = v.varargize(callsite.mpropdef, recv, self.raw_arguments)
2802 return v.compile_callsite(callsite, args)
2806 redef class ASendReassignFormExpr
2809 var recv = v.expr(self.n_expr, null)
2810 var callsite = self.callsite.as(not null)
2811 var args = v.varargize(callsite.mpropdef, recv, self.raw_arguments)
2813 var value = v.expr(self.n_value, null)
2815 var left = v.compile_callsite(callsite, args)
2818 var res = v.compile_callsite(self.reassign_callsite.as(not null), [left, value])
2822 v.compile_callsite(self.write_callsite.as(not null), args)
2826 redef class ASuperExpr
2829 var recv = v.frame.arguments.first
2831 var callsite = self.callsite
2832 if callsite != null then
2833 var args = v.varargize(callsite.mpropdef, recv, self.n_args.n_exprs)
2835 # Add additional arguments for the super init call
2836 if args.length == 1 then
2837 for i in [0..callsite.msignature.arity[ do
2838 args.add(v.frame.arguments[i+1])
2842 var res = v.compile_callsite(callsite, args)
2846 var mpropdef = self.mpropdef.as(not null)
2847 var args = v.varargize(mpropdef, recv, self.n_args.n_exprs)
2848 if args.length == 1 then
2849 args = v.frame.arguments
2852 # stantard call-next-method
2853 return v.supercall(mpropdef, recv.mtype.as(MClassType), args)
2857 redef class ANewExpr
2860 var mtype = self.recvtype
2861 assert mtype != null
2863 var ctype = mtype.ctype
2864 if mtype.mclass.name == "NativeArray" then
2865 assert self.n_args.n_exprs.length == 1
2866 var l = v.expr(self.n_args.n_exprs.first, null)
2867 assert mtype isa MGenericType
2868 var elttype = mtype.arguments.first
2869 return v.native_array_instance(elttype, l)
2870 else if ctype == "val*" then
2871 recv = v.init_instance(mtype)
2872 else if ctype == "char*" then
2873 recv = v.new_expr("NULL/*special!*/", mtype)
2875 recv = v.new_expr("({ctype})0/*special!*/", mtype)
2878 var callsite = self.callsite.as(not null)
2879 var args = v.varargize(callsite.mpropdef, recv, self.n_args.n_exprs)
2880 var res2 = v.compile_callsite(callsite, args)
2881 if res2 != null then
2882 #self.debug("got {res2} from {mproperty}. drop {recv}")
2889 redef class AAttrExpr
2892 var recv = v.expr(self.n_expr, null)
2893 var mproperty = self.mproperty.as(not null)
2894 return v.read_attribute(mproperty, recv)
2898 redef class AAttrAssignExpr
2901 var recv = v.expr(self.n_expr, null)
2902 var i = v.expr(self.n_value, null)
2903 var mproperty = self.mproperty.as(not null)
2904 v.write_attribute(mproperty, recv, i)
2909 redef class AAttrReassignExpr
2912 var recv = v.expr(self.n_expr, null)
2913 var value = v.expr(self.n_value, null)
2914 var mproperty = self.mproperty.as(not null)
2915 var attr = v.read_attribute(mproperty, recv)
2916 var res = v.compile_callsite(self.reassign_callsite.as(not null), [attr, value])
2918 v.write_attribute(mproperty, recv, res)
2922 redef class AIssetAttrExpr
2925 var recv = v.expr(self.n_expr, null)
2926 var mproperty = self.mproperty.as(not null)
2927 return v.isset_attribute(mproperty, recv)
2931 redef class ADebugTypeExpr
2940 redef class Array[E]
2941 # Return a new `Array` with the elements only contened in self and not in `o
`
2942 fun -(o: Array[E]): Array[E] do
2943 var res = new Array[E]
2944 for e in self do if not o.has(e) then res.add(e)
2950 # All `MProperty` associated to all `MClassDef` of `mclass
`
2951 fun properties(mclass: MClass): Set[MProperty] do
2952 if not self.properties_cache.has_key(mclass) then
2953 var properties = new HashSet[MProperty]
2954 var parents = new Array[MClass]
2955 if self.flatten_mclass_hierarchy.has(mclass) then
2956 parents.add_all(mclass.in_hierarchy(self).direct_greaters)
2958 for parent in parents do
2959 properties.add_all(self.properties(parent))
2961 for mclassdef in mclass.mclassdefs do
2962 if not self.in_importation <= mclassdef.mmodule then continue
2963 for mprop in mclassdef.intro_mproperties do
2964 properties.add(mprop)
2967 self.properties_cache[mclass] = properties
2969 return properties_cache[mclass]
2971 private var properties_cache: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
2973 # Write FFI and nitni results to file
2974 fun finalize_ffi(c: AbstractCompiler) do end
2976 # Give requided addinional system libraries (as given to LD_LIBS)
2977 # Note: can return null instead of an empty set
2978 fun collect_linker_libs: nullable Set[String] do return null
2981 # Create a tool context to handle options and paths
2982 var toolcontext = new ToolContext
2984 toolcontext.tooldescription = "Usage: nitc [OPTION]... file.nit...\nCompiles Nit programs."
2986 # We do not add other options, so process them now!
2987 toolcontext.process_options(args)
2989 # We need a model to collect stufs
2990 var model = new Model
2991 # An a model builder to parse files
2992 var modelbuilder = new ModelBuilder(model, toolcontext)
2994 var arguments = toolcontext.option_context.rest
2995 if arguments.length > 1 and toolcontext.opt_output.value != null then
2996 print "Error: --output needs a single source file. Do you prefer --dir?"
3000 # Here we load an process all modules passed on the command line
3001 var mmodules = modelbuilder.parse(arguments)
3003 if mmodules.is_empty then return
3004 modelbuilder.run_phases
3006 for mmodule in mmodules do
3007 toolcontext.info("*** PROCESS {mmodule} ***", 1)
3009 toolcontext.run_global_phases(ms)