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
26 # Add compiling options
27 redef class ToolContext
29 var opt_output
: OptionString = new OptionString("Output file", "-o", "--output")
31 var opt_dir
: OptionString = new OptionString("Output directory", "--dir")
33 var opt_no_cc
: OptionBool = new OptionBool("Do not invoke C compiler", "--no-cc")
35 var opt_no_main
: OptionBool = new OptionBool("Do not generate main entry point", "--no-main")
37 var opt_cc_path
: OptionArray = new OptionArray("Set include path for C header files (may be used more than once)", "--cc-path")
39 var opt_make_flags
: OptionString = new OptionString("Additional options to make", "--make-flags")
41 var opt_compile_dir
: OptionString = new OptionString("Directory used to generate temporary files", "--compile-dir")
43 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")
46 # --no-check-attr-isset
47 var opt_no_check_attr_isset
: OptionBool = new OptionBool("Disable isset tests before each attribute access (dangerous)", "--no-check-attr-isset")
49 var opt_no_check_assert
: OptionBool = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
51 var opt_no_check_autocast
: OptionBool = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
53 var opt_no_check_null
: OptionBool = new OptionBool("Disable tests of null receiver (dangerous)", "--no-check-null")
55 var opt_no_check_all
: OptionBool = new OptionBool("Disable all tests (dangerous)", "--no-check-all")
56 # --typing-test-metrics
57 var opt_typing_test_metrics
: OptionBool = new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
58 # --invocation-metrics
59 var opt_invocation_metrics
: OptionBool = new OptionBool("Enable static and dynamic count of all method invocations", "--invocation-metrics")
60 # --isset-checks-metrics
61 var opt_isset_checks_metrics
: OptionBool = new OptionBool("Enable static and dynamic count of isset checks before attributes access", "--isset-checks-metrics")
63 var opt_stacktrace
: OptionString = new OptionString("Control the generation of stack traces", "--stacktrace")
65 var opt_no_gcc_directive
= new OptionArray("Disable a advanced gcc directives for optimization", "--no-gcc-directive")
67 var opt_release
= new OptionBool("Compile in release mode and finalize application", "--release")
72 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
)
73 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
)
74 self.option_context
.add_option
(self.opt_typing_test_metrics
, self.opt_invocation_metrics
, self.opt_isset_checks_metrics
)
75 self.option_context
.add_option
(self.opt_stacktrace
)
76 self.option_context
.add_option
(self.opt_no_gcc_directive
)
77 self.option_context
.add_option
(self.opt_release
)
80 redef fun process_options
(args
)
84 var st
= opt_stacktrace
.value
85 if st
== "none" or st
== "libunwind" or st
== "nitstack" then
87 else if st
== "auto" or st
== null then
89 opt_stacktrace
.value
= "nitstack"
91 print
"Error: unknown value `{st}` for --stacktrace. Use `none`, `libunwind`, `nitstack` or `auto`."
95 if opt_output
.value
!= null and opt_dir
.value
!= null then
96 print
"Error: cannot use both --dir and --output"
100 if opt_no_check_all
.value
then
101 opt_no_check_covariance
.value
= true
102 opt_no_check_attr_isset
.value
= true
103 opt_no_check_assert
.value
= true
104 opt_no_check_autocast
.value
= true
105 opt_no_check_null
.value
= true
110 redef class ModelBuilder
111 # The compilation directory
112 var compile_dir
: String
114 # Simple indirection to `Toolchain::write_and_make`
115 protected fun write_and_make
(compiler
: AbstractCompiler)
117 var platform
= compiler
.mainmodule
.target_platform
119 if platform
== null then
120 toolchain
= new MakefileToolchain(toolcontext
)
122 toolchain
= platform
.toolchain
(toolcontext
)
124 compile_dir
= toolchain
.compile_dir
125 toolchain
.write_and_make compiler
130 fun toolchain
(toolcontext
: ToolContext): Toolchain is abstract
134 var toolcontext
: ToolContext
136 fun compile_dir
: String
138 var compile_dir
= toolcontext
.opt_compile_dir
.value
139 if compile_dir
== null then compile_dir
= ".nit_compile"
143 fun write_and_make
(compiler
: AbstractCompiler) is abstract
146 class MakefileToolchain
148 # The list of directories to search for included C headers (-I for C compilers)
149 # The list is initially set with :
150 # * the toolcontext --cc-path option
151 # * the NIT_CC_PATH environment variable
152 # * `toolcontext.nit_dir`
153 # Path can be added (or removed) by the client
154 var cc_paths
= new Array[String]
156 protected fun gather_cc_paths
158 # Look for the the Nit clib path
159 var path_env
= toolcontext
.nit_dir
160 if path_env
!= null then
161 var libname
= "{path_env}/clib"
162 if libname
.file_exists
then cc_paths
.add
(libname
)
165 if cc_paths
.is_empty
then
166 toolcontext
.error
(null, "Cannot determine the nit clib path. define envvar NIT_DIR.")
169 # Add user defined cc_paths
170 cc_paths
.append
(toolcontext
.opt_cc_path
.value
)
172 path_env
= "NIT_CC_PATH".environ
173 if not path_env
.is_empty
then
174 cc_paths
.append
(path_env
.split_with
(':'))
178 redef fun write_and_make
(compiler
)
182 var mainmodule
= compiler
.mainmodule
183 var compile_dir
= compile_dir
185 # Generate the .h and .c files
186 # A single C file regroups many compiled rumtime functions
187 # 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
189 self.toolcontext
.info
("*** WRITING C ***", 1)
193 var cfiles
= new Array[String]
194 write_files
(compiler
, compile_dir
, cfiles
)
196 # Generate the Makefile
198 write_makefile
(compiler
, compile_dir
, cfiles
)
201 self.toolcontext
.info
("*** END WRITING C: {time1-time0} ***", 2)
203 # Execute the Makefile
205 if self.toolcontext
.opt_no_cc
.value
then return
208 self.toolcontext
.info
("*** COMPILING C ***", 1)
210 compile_c_code
(compiler
, compile_dir
)
213 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
216 fun write_files
(compiler
: AbstractCompiler, compile_dir
: String, cfiles
: Array[String])
218 var platform
= compiler
.mainmodule
.target_platform
219 if self.toolcontext
.opt_stacktrace
.value
== "nitstack" and (platform
== null or platform
.supports_libunwind
) then compiler
.build_c_to_nit_bindings
220 var cc_opt_with_libgc
= "-DWITH_LIBGC"
221 if platform
!= null and not platform
.supports_libgc
then cc_opt_with_libgc
= ""
223 # Add gc_choser.h to aditionnal bodies
224 var gc_chooser
= new ExternCFile("gc_chooser.c", cc_opt_with_libgc
)
225 compiler
.extern_bodies
.add
(gc_chooser
)
226 compiler
.files_to_copy
.add
"{cc_paths.first}/gc_chooser.c"
227 compiler
.files_to_copy
.add
"{cc_paths.first}/gc_chooser.h"
230 var m2m
= toolcontext
.modelbuilder
.mmodule2nmodule
231 for m
in compiler
.mainmodule
.in_importation
.greaters
do
232 compiler
.finalize_ffi_for_module
(m
)
235 # Copy original .[ch] files to compile_dir
236 for src
in compiler
.files_to_copy
do
237 var basename
= src
.basename
("")
238 var dst
= "{compile_dir}/{basename}"
242 var hfilename
= compiler
.header
.file
.name
+ ".h"
243 var hfilepath
= "{compile_dir}/{hfilename}"
244 var h
= new OFStream.open
(hfilepath
)
245 for l
in compiler
.header
.decl_lines
do
249 for l
in compiler
.header
.lines
do
255 for f
in compiler
.files
do
257 var hfile
: nullable OFStream = null
259 var cfilename
= "{f.name}.0.h"
260 var cfilepath
= "{compile_dir}/{cfilename}"
261 hfile
= new OFStream.open
(cfilepath
)
262 hfile
.write
"#include \"{hfilename}\
"\n"
263 for key
in f
.required_declarations
do
264 if not compiler
.provided_declarations
.has_key
(key
) then
265 var node
= compiler
.requirers_of_declarations
.get_or_null
(key
)
267 node
.debug
"No provided declaration for {key}"
269 print
"No provided declaration for {key}"
273 hfile
.write compiler
.provided_declarations
[key
]
277 var file
: nullable OFStream = null
278 for vis
in f
.writers
do
279 if vis
== compiler
.header
then continue
280 var total_lines
= vis
.lines
.length
+ vis
.decl_lines
.length
281 if total_lines
== 0 then continue
283 if file
== null or count
> 10000 then
285 if file
!= null then file
.close
286 cfilename
= "{f.name}.{i}.c"
287 cfilepath
= "{compile_dir}/{cfilename}"
288 self.toolcontext
.info
("new C source files to compile: {cfilepath}", 3)
289 cfiles
.add
(cfilename
)
290 file
= new OFStream.open
(cfilepath
)
291 file
.write
"#include \"{f.name}.0.h\
"\n"
294 for l
in vis
.decl_lines
do
298 for l
in vis
.lines
do
303 if file
!= null then file
.close
306 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
309 fun makefile_name
(mainmodule
: MModule): String do return "{mainmodule.name}.mk"
311 fun default_outname
(mainmodule
: MModule): String do return mainmodule
.name
313 # Combine options and platform informations to get the final path of the outfile
314 fun outfile
(mainmodule
: MModule): String
316 var res
= self.toolcontext
.opt_output
.value
317 if res
!= null then return res
318 res
= default_outname
(mainmodule
)
319 var dir
= self.toolcontext
.opt_dir
.value
320 if dir
!= null then return dir
.join_path
(res
)
324 fun write_makefile
(compiler
: AbstractCompiler, compile_dir
: String, cfiles
: Array[String])
326 var mainmodule
= compiler
.mainmodule
327 var platform
= compiler
.mainmodule
.target_platform
329 var outname
= outfile
(mainmodule
)
331 var orig_dir
= compile_dir
.relpath
(".")
332 var outpath
= orig_dir
.join_path
(outname
).simplify_path
333 var makename
= makefile_name
(mainmodule
)
334 var makepath
= "{compile_dir}/{makename}"
335 var makefile
= new OFStream.open
(makepath
)
339 cc_includes
+= " -I \"" + p + "\
""
342 var linker_options
= new HashSet[String]
343 var m2m
= toolcontext
.modelbuilder
.mmodule2nmodule
344 for m
in mainmodule
.in_importation
.greaters
do
345 var libs
= m
.collect_linker_libs
346 if libs
!= null then linker_options
.add_all
(libs
)
349 makefile
.write
("CC = ccache cc\nCXX = ccache c++\nCFLAGS = -g -O2 -Wno-unused-value -Wno-switch\nCINCL = {cc_includes}\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc {linker_options.join(" ")}\n\n")
351 var ost
= toolcontext
.opt_stacktrace
.value
352 if (ost
== "libunwind" or ost
== "nitstack") and (platform
== null or platform
.supports_libunwind
) then makefile
.write
("NEED_LIBUNWIND := YesPlease\n")
354 # Dynamic adaptations
355 # While `platform` enable complex toolchains, they are statically applied
356 # For a dynamic adaptsation of the compilation, the generated Makefile should check and adapt things itself
358 # Check and adapt the targeted system
359 makefile
.write
("uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n")
360 makefile
.write
("ifeq ($(uname_S),Darwin)\n")
361 # remove -lunwind since it is already included on macosx
362 makefile
.write
("\tNEED_LIBUNWIND :=\n")
363 makefile
.write
("endif\n\n")
365 # Check and adapt for the compiler used
366 # clang need an additionnal `-Qunused-arguments`
367 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")
369 makefile
.write
("ifdef NEED_LIBUNWIND\n\tLDLIBS += -lunwind\nendif\n")
371 makefile
.write
("all: {outpath}\n\n")
373 var ofiles
= new Array[String]
374 var dep_rules
= new Array[String]
375 # Compile each generated file
377 var o
= f
.strip_extension
(".c") + ".o"
378 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) $(CINCL) -c -o {o} {f}\n\n")
383 var java_files
= new Array[ExternFile]
385 # Compile each required extern body into a specific .o
386 for f
in compiler
.extern_bodies
do
387 var o
= f
.makefile_rule_name
388 var ff
= f
.filename
.basename
("")
389 makefile
.write
("{o}: {ff}\n")
390 makefile
.write
("\t{f.makefile_rule_content}\n\n")
391 dep_rules
.add
(f
.makefile_rule_name
)
393 if f
.compiles_to_o_file
then ofiles
.add
(o
)
394 if f
.add_to_jar
then java_files
.add
(f
)
397 if not java_files
.is_empty
then
398 var jar_file
= "{outpath}.jar"
400 var class_files_array
= new Array[String]
401 for f
in java_files
do class_files_array
.add
(f
.makefile_rule_name
)
402 var class_files
= class_files_array
.join
(" ")
404 makefile
.write
("{jar_file}: {class_files}\n")
405 makefile
.write
("\tjar cf {jar_file} {class_files}\n\n")
406 dep_rules
.add jar_file
410 makefile
.write
("{outpath}: {dep_rules.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outpath} {ofiles.join(" ")} $(LDLIBS)\n\n")
412 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
414 self.toolcontext
.info
("Generated makefile: {makepath}", 2)
417 fun compile_c_code
(compiler
: AbstractCompiler, compile_dir
: String)
419 var makename
= makefile_name
(compiler
.mainmodule
)
421 var makeflags
= self.toolcontext
.opt_make_flags
.value
422 if makeflags
== null then makeflags
= ""
423 self.toolcontext
.info
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags}", 2)
426 if self.toolcontext
.verbose_level
>= 3 then
427 res
= sys
.system
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1")
429 res
= sys
.system
("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
432 toolcontext
.error
(null, "make failed! Error code: {res}.")
437 # Singleton that store the knowledge about the compilation process
438 abstract class AbstractCompiler
439 type VISITOR: AbstractCompilerVisitor
441 # Table corresponding c_names to nit names (methods)
442 var names
= new HashMap[String, String]
444 # The main module of the program currently compiled
445 # Is assigned during the separate compilation
446 var mainmodule
: MModule is writable
448 # The real main module of the program
449 var realmainmodule
: MModule
451 # The modeulbuilder used to know the model and the AST
452 var modelbuilder
: ModelBuilder is protected writable
454 # Is hardening asked? (see --hardening)
455 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
457 init(mainmodule
: MModule, modelbuilder
: ModelBuilder)
459 self.mainmodule
= mainmodule
460 self.realmainmodule
= mainmodule
461 self.modelbuilder
= modelbuilder
464 # Force the creation of a new file
465 # The point is to avoid contamination between must-be-compiled-separately files
466 fun new_file
(name
: String): CodeFile
468 var f
= new CodeFile(name
)
473 # The list of all associated files
474 # Used to generate .c files
475 var files
: List[CodeFile] = new List[CodeFile]
477 # Initialize a visitor specific for a compiler engine
478 fun new_visitor
: VISITOR is abstract
480 # Where global declaration are stored (the main .h)
481 var header
: CodeWriter is writable
483 # Provide a declaration that can be requested (before or latter) by a visitor
484 fun provide_declaration
(key
: String, s
: String)
486 if self.provided_declarations
.has_key
(key
) then
487 assert self.provided_declarations
[key
] == s
489 self.provided_declarations
[key
] = s
492 private var provided_declarations
= new HashMap[String, String]
494 private var requirers_of_declarations
= new HashMap[String, ANode]
496 # Builds the .c and .h files to be used when generating a Stack Trace
497 # Binds the generated C function names to Nit function names
498 fun build_c_to_nit_bindings
500 var compile_dir
= modelbuilder
.compile_dir
502 var stream
= new OFStream.open
("{compile_dir}/c_functions_hash.c")
503 stream
.write
("#include <string.h>\n")
504 stream
.write
("#include <stdlib.h>\n")
505 stream
.write
("#include \"c_functions_hash
.h\
"\n")
506 stream
.write
("typedef struct C_Nit_Names\{char* name; char* nit_name;\}C_Nit_Names;\n")
507 stream
.write
("const char* get_nit_name(register const char* procproc, register unsigned int len)\{\n")
508 stream
.write
("char* procname = malloc(len+1);")
509 stream
.write
("memcpy(procname, procproc, len);")
510 stream
.write
("procname[len] = '\\0';")
511 stream
.write
("static const C_Nit_Names map[{names.length}] = \{\n")
512 for i
in names
.keys
do
515 stream.write("\
",\"")
516 stream.write(names[i])
517 stream.write("\
"\},\n")
519 stream
.write
("\};\n")
520 stream
.write
("int i;")
521 stream
.write
("for(i = 0; i < {names.length}; i++)\{")
522 stream
.write
("if(strcmp(procname,map[i].name) == 0)\{")
523 stream
.write
("free(procname);")
524 stream
.write
("return map[i].nit_name;")
527 stream
.write
("free(procname);")
528 stream
.write
("return NULL;")
532 stream
= new OFStream.open
("{compile_dir}/c_functions_hash.h")
533 stream
.write
("const char* get_nit_name(register const char* procname, register unsigned int len);\n")
536 extern_bodies
.add
(new ExternCFile("{compile_dir}/c_functions_hash.c", ""))
540 # This method call compile_header_strucs method that has to be refined
541 fun compile_header
do
543 var toolctx
= modelbuilder
.toolcontext
544 self.header
.add_decl
("#include <stdlib.h>")
545 self.header
.add_decl
("#include <stdio.h>")
546 self.header
.add_decl
("#include <string.h>")
547 self.header
.add_decl
("#include \"gc_chooser
.h\
"")
548 self.header
.add_decl
("#ifdef ANDROID")
549 self.header
.add_decl
(" #include <android/log.h>")
550 self.header
.add_decl
(" #define PRINT_ERROR(...) (void)__android_log_print(ANDROID_LOG_WARN, \"Nit\
", __VA_ARGS__)")
551 self.header
.add_decl
("#else")
552 self.header
.add_decl
(" #define PRINT_ERROR(...) fprintf(stderr, __VA_ARGS__)")
553 self.header
.add_decl
("#endif")
555 compile_header_structs
556 compile_nitni_structs
558 var gccd_disable
= modelbuilder
.toolcontext
.opt_no_gcc_directive
.value
559 if gccd_disable
.has
("noreturn") or gccd_disable
.has
("all") then
560 # Signal handler function prototype
561 self.header
.add_decl
("void show_backtrace(int);")
563 self.header
.add_decl
("void show_backtrace(int) __attribute__ ((noreturn));")
566 if gccd_disable
.has
("likely") or gccd_disable
.has
("all") then
567 self.header
.add_decl
("#define likely(x) (x)")
568 self.header
.add_decl
("#define unlikely(x) (x)")
569 else if gccd_disable
.has
("correct-likely") then
570 # invert the `likely` definition
571 # Used by masochists to bench the worst case
572 self.header
.add_decl
("#define likely(x) __builtin_expect((x),0)")
573 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),1)")
575 self.header
.add_decl
("#define likely(x) __builtin_expect((x),1)")
576 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),0)")
579 # Global variable used by intern methods
580 self.header
.add_decl
("extern int glob_argc;")
581 self.header
.add_decl
("extern char **glob_argv;")
582 self.header
.add_decl
("extern val *glob_sys;")
585 # Declaration of structures for live Nit types
586 protected fun compile_header_structs
is abstract
588 # Declaration of structures for nitni undelying the FFI
589 protected fun compile_nitni_structs
591 self.header
.add_decl
"""
592 /* Native reference to Nit objects */
593 /* This structure is used to represent every Nit type in extern methods and custom C code. */
595 struct nitni_ref *next,
596 *prev; /* adjacent global references in global list */
597 int count; /* number of time this global reference has been marked */
600 /* List of global references from C code to Nit objects */
601 /* Instanciated empty at init of Nit system and filled explicitly by user in C code */
602 struct nitni_global_ref_list_t {
603 struct nitni_ref *head, *tail;
605 extern struct nitni_global_ref_list_t *nitni_global_ref_list;
607 /* Initializer of global reference list */
608 extern void nitni_global_ref_list_init();
610 /* Intern function to add a global reference to the list */
611 extern void nitni_global_ref_add( struct nitni_ref *ref );
613 /* Intern function to remove a global reference from the list */
614 extern void nitni_global_ref_remove( struct nitni_ref *ref );
616 /* Increase count on an existing global reference */
617 extern void nitni_global_ref_incr( struct nitni_ref *ref );
619 /* Decrease count on an existing global reference */
620 extern void nitni_global_ref_decr( struct nitni_ref *ref );
624 fun compile_finalizer_function
626 var finalizable_type
= mainmodule
.finalizable_type
627 if finalizable_type
== null then return
629 var finalize_meth
= mainmodule
.try_get_primitive_method
("finalize", finalizable_type
.mclass
)
631 if finalize_meth
== null then
632 modelbuilder
.toolcontext
.error
(null, "The `Finalizable` class doesn't declare the `finalize` method.")
636 var v
= self.new_visitor
637 v
.add_decl
"void gc_finalize (void *obj, void *client_data) \{"
638 var recv
= v
.new_expr
("obj", finalizable_type
)
639 v
.send
(finalize_meth
, [recv
])
643 # Generate the main C function.
647 # * allocate the Sys object if it exists
648 # * call init if is exists
649 # * call main if it exists
650 fun compile_main_function
652 var v
= self.new_visitor
653 v
.add_decl
("#include <signal.h>")
654 var ost
= modelbuilder
.toolcontext
.opt_stacktrace
.value
655 var platform
= mainmodule
.target_platform
657 if platform
!= null and not platform
.supports_libunwind
then ost
= "none"
659 var no_main
= (platform
!= null and platform
.no_main
) or modelbuilder
.toolcontext
.opt_no_main
.value
661 if ost
== "nitstack" or ost
== "libunwind" then
662 v
.add_decl
("#define UNW_LOCAL_ONLY")
663 v
.add_decl
("#include <libunwind.h>")
664 if ost
== "nitstack" then
665 v
.add_decl
("#include \"c_functions_hash
.h\
"")
668 v
.add_decl
("int glob_argc;")
669 v
.add_decl
("char **glob_argv;")
670 v
.add_decl
("val *glob_sys;")
672 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
673 for tag
in count_type_test_tags
do
674 v
.add_decl
("long count_type_test_resolved_{tag};")
675 v
.add_decl
("long count_type_test_unresolved_{tag};")
676 v
.add_decl
("long count_type_test_skipped_{tag};")
677 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
678 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
679 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
683 if self.modelbuilder
.toolcontext
.opt_invocation_metrics
.value
then
684 v
.add_decl
("long count_invoke_by_tables;")
685 v
.add_decl
("long count_invoke_by_direct;")
686 v
.add_decl
("long count_invoke_by_inline;")
687 v
.compiler
.header
.add_decl
("extern long count_invoke_by_tables;")
688 v
.compiler
.header
.add_decl
("extern long count_invoke_by_direct;")
689 v
.compiler
.header
.add_decl
("extern long count_invoke_by_inline;")
692 if self.modelbuilder
.toolcontext
.opt_isset_checks_metrics
.value
then
693 v
.add_decl
("long count_attr_reads = 0;")
694 v
.add_decl
("long count_isset_checks = 0;")
695 v
.compiler
.header
.add_decl
("extern long count_attr_reads;")
696 v
.compiler
.header
.add_decl
("extern long count_isset_checks;")
699 v
.add_decl
("void sig_handler(int signo)\{")
700 v
.add_decl
("PRINT_ERROR(\"Caught signal
: %s\\n\
", strsignal(signo));")
701 v
.add_decl
("show_backtrace(signo);")
704 v
.add_decl
("void show_backtrace (int signo) \{")
705 if ost
== "nitstack" or ost
== "libunwind" then
706 v
.add_decl
("char* opt = getenv(\"NIT_NO_STACK\
");")
707 v
.add_decl
("unw_cursor_t cursor;")
708 v
.add_decl
("if(opt==NULL)\{")
709 v
.add_decl
("unw_context_t uc;")
710 v
.add_decl
("unw_word_t ip;")
711 v
.add_decl
("char* procname = malloc(sizeof(char) * 100);")
712 v
.add_decl
("unw_getcontext(&uc);")
713 v
.add_decl
("unw_init_local(&cursor, &uc);")
714 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
715 v
.add_decl
("PRINT_ERROR(\"-- Stack Trace ------------------------------\\n\
");")
716 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
717 v
.add_decl
("while (unw_step(&cursor) > 0) \{")
718 v
.add_decl
(" unw_get_proc_name(&cursor, procname, 100, &ip);")
719 if ost
== "nitstack" then
720 v
.add_decl
(" const char* recv = get_nit_name(procname, strlen(procname));")
721 v
.add_decl
(" if (recv != NULL)\{")
722 v
.add_decl
(" PRINT_ERROR(\"` %s\\n\", recv);")
723 v.add_decl(" \}else\{")
724 v.add_decl(" PRINT_ERROR(\"` %s\\n\
", procname);")
727 v
.add_decl
(" PRINT_ERROR(\"` %s \\n\",procname);")
730 v.add_decl("PRINT_ERROR(\"-------------------------------------------------\\n\");")
731 v.add_decl("free(procname);")
734 v.add_decl("exit(signo);")
738 v.add_decl("int nit_main(int argc, char** argv) \{")
740 v.add_decl("int main(int argc, char** argv) \{")
743 v.add("signal(SIGABRT, sig_handler);")
744 v.add("signal(SIGFPE, sig_handler);")
745 v.add("signal(SIGILL, sig_handler);")
746 v.add("signal(SIGINT, sig_handler);")
747 v.add("signal(SIGTERM, sig_handler);")
748 v.add("signal(SIGSEGV, sig_handler);")
749 v.add("signal(SIGPIPE, sig_handler);")
751 v.add("glob_argc = argc; glob_argv = argv;")
752 v.add("initialize_gc_option();")
754 v.add "initialize_nitni_global_refs();"
756 var main_type = mainmodule.sys_type
757 if main_type != null then
758 var mainmodule = v.compiler.mainmodule
759 var glob_sys = v.init_instance(main_type)
760 v.add("glob_sys = {glob_sys};")
761 var main_init = mainmodule.try_get_primitive_method("init", main_type.mclass)
762 if main_init != null then
763 v.send(main_init, [glob_sys])
765 var main_method = mainmodule.try_get_primitive_method("run", main_type.mclass) or else
766 mainmodule.try_get_primitive_method("main", main_type.mclass)
767 if main_method != null then
768 v.send(main_method, [glob_sys])
772 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
773 v.add_decl("long count_type_test_resolved_total = 0;")
774 v.add_decl("long count_type_test_unresolved_total = 0;")
775 v.add_decl("long count_type_test_skipped_total = 0;")
776 v.add_decl("long count_type_test_total_total = 0;")
777 for tag in count_type_test_tags do
778 v.add_decl("long count_type_test_total_{tag};")
779 v.add("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
780 v.add("count_type_test_resolved_total += count_type_test_resolved_{tag};")
781 v.add("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
782 v.add("count_type_test_skipped_total += count_type_test_skipped_{tag};")
783 v.add("count_type_test_total_total += count_type_test_total_{tag};")
785 v.add("printf(\"# dynamic count_type_test: total %l\\n\");")
786 v.add("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\");")
787 var tags = count_type_test_tags.to_a
790 v.add("printf(\"{tag}\");")
791 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
792 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
793 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
794 v.add("printf(\"\\t%ld (%.2f%%)\\n\", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
798 if self.modelbuilder.toolcontext.opt_invocation_metrics.value then
799 v.add_decl("long count_invoke_total;")
800 v.add("count_invoke_total = count_invoke_by_tables + count_invoke_by_direct + count_invoke_by_inline;")
801 v.add("printf(\"# dynamic count_invocation: total %ld\\n\", count_invoke_total);")
802 v.add("printf(\"by table: %ld (%.2f%%)\\n\", count_invoke_by_tables, 100.0*count_invoke_by_tables/count_invoke_total);")
803 v.add("printf(\"direct: %ld (%.2f%%)\\n\", count_invoke_by_direct, 100.0*count_invoke_by_direct/count_invoke_total);")
804 v.add("printf(\"inlined: %ld (%.2f%%)\\n\", count_invoke_by_inline, 100.0*count_invoke_by_inline/count_invoke_total);")
807 if self.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
808 v.add("printf(\"# dynamic attribute reads: %ld\\n\", count_attr_reads);")
809 v.add("printf(\"# dynamic isset checks: %ld\\n\", count_isset_checks);")
816 # Copile all C functions related to the [incr|decr]_ref features of the FFI
817 fun compile_nitni_global_ref_functions
819 var v = self.new_visitor
821 struct nitni_global_ref_list_t *nitni_global_ref_list;
822 void initialize_nitni_global_refs() {
823 nitni_global_ref_list = (struct nitni_global_ref_list_t*)nit_alloc(sizeof(struct nitni_global_ref_list_t));
824 nitni_global_ref_list->head = NULL;
825 nitni_global_ref_list->tail = NULL;
828 void nitni_global_ref_add( struct nitni_ref *ref ) {
829 if ( nitni_global_ref_list->head == NULL ) {
830 nitni_global_ref_list->head = ref;
833 nitni_global_ref_list->tail->next = ref;
834 ref->prev = nitni_global_ref_list->tail;
836 nitni_global_ref_list->tail = ref;
841 void nitni_global_ref_remove( struct nitni_ref *ref ) {
842 if ( ref->prev == NULL ) {
843 nitni_global_ref_list->head = ref->next;
845 ref->prev->next = ref->next;
848 if ( ref->next == NULL ) {
849 nitni_global_ref_list->tail = ref->prev;
851 ref->next->prev = ref->prev;
855 extern void nitni_global_ref_incr( struct nitni_ref *ref ) {
856 if ( ref->count == 0 ) /* not registered */
859 nitni_global_ref_add( ref );
865 extern void nitni_global_ref_decr( struct nitni_ref *ref ) {
866 if ( ref->count == 1 ) /* was last reference */
868 /* remove from list */
869 nitni_global_ref_remove( ref );
877 # List of additional files required to compile (FFI)
878 var extern_bodies = new Array[ExternFile]
880 # List of source files to copy over to the compile dir
881 var files_to_copy = new Array[String]
883 # This is used to avoid adding an extern file more than once
884 private var seen_extern = new ArraySet[String]
886 # Generate code that initialize the attributes on a new instance
887 fun generate_init_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
889 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
890 self.mainmodule.linearize_mclassdefs(cds)
892 var n = self.modelbuilder.mclassdef2nclassdef[cd]
893 for npropdef in n.n_propdefs do
894 if npropdef isa AAttrPropdef then
895 npropdef.init_expr(v, recv)
901 # Generate code that check if an attribute is correctly initialized
902 fun generate_check_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
904 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
905 self.mainmodule.linearize_mclassdefs(cds)
907 var n = self.modelbuilder.mclassdef2nclassdef[cd]
908 for npropdef in n.n_propdefs do
909 if npropdef isa AAttrPropdef then
910 npropdef.check_expr(v, recv)
918 var count_type_test_tags: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
919 var count_type_test_resolved: HashMap[String, Int] = init_count_type_test_tags
920 var count_type_test_unresolved: HashMap[String, Int] = init_count_type_test_tags
921 var count_type_test_skipped: HashMap[String, Int] = init_count_type_test_tags
923 protected fun init_count_type_test_tags: HashMap[String, Int]
925 var res = new HashMap[String, Int]
926 for tag in count_type_test_tags do
932 # Display stats about compilation process
936 # * type tests against resolved types (`x
isa Collection[Animal]`)
937 # * type tests against unresolved types (`x
isa Collection[E
]`)
938 # * type tests skipped
942 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
943 print "# static count_type_test"
944 print "\tresolved:\tunresolved\tskipped\ttotal"
945 var count_type_test_total = init_count_type_test_tags
946 count_type_test_resolved["total"] = 0
947 count_type_test_unresolved["total"] = 0
948 count_type_test_skipped["total"] = 0
949 count_type_test_total["total"] = 0
950 for tag in count_type_test_tags do
951 count_type_test_total[tag] = count_type_test_resolved[tag] + count_type_test_unresolved[tag] + count_type_test_skipped[tag]
952 count_type_test_resolved["total"] += count_type_test_resolved[tag]
953 count_type_test_unresolved["total"] += count_type_test_unresolved[tag]
954 count_type_test_skipped["total"] += count_type_test_skipped[tag]
955 count_type_test_total["total"] += count_type_test_total[tag]
957 var count_type_test = count_type_test_total["total"]
958 var tags = count_type_test_tags.to_a
962 printn "\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
963 printn "\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
964 printn "\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
965 printn "\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
971 fun finalize_ffi_for_module(mmodule: MModule) do mmodule.finalize_ffi(self)
974 # Avoid division by zero by returning the string "n/a"
975 fun div(a,b:Int):String
977 if b == 0 then return "n/a"
978 return ((a*10000/b).to_f / 100.0).to_precision(2)
982 # A file unit (may be more than one file if
983 # A file unit aim to be autonomous and is made or one or more `CodeWriter`s
986 var writers = new Array[CodeWriter]
987 var required_declarations = new HashSet[String]
990 # Where to store generated lines
993 var lines: List[String] = new List[String]
994 var decl_lines: List[String] = new List[String]
996 # Add a line in the main part of the generated C
997 fun add(s: String) do self.lines.add(s)
1000 # (used for local or global declaration)
1001 fun add_decl(s: String) do self.decl_lines.add(s)
1003 init(file: CodeFile)
1006 file.writers.add(self)
1010 # A visitor on the AST of property definition that generate the C code.
1011 abstract class AbstractCompilerVisitor
1013 type COMPILER: AbstractCompiler
1015 # The associated compiler
1016 var compiler: COMPILER
1018 # The current visited AST node
1019 var current_node: nullable ANode = null is writable
1021 # The current `Frame`
1022 var frame: nullable Frame is writable
1024 # Alias for self.compiler.mainmodule.object_type
1025 fun object_type: MClassType do return self.compiler.mainmodule.object_type
1027 # Alias for self.compiler.mainmodule.bool_type
1028 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
1030 var writer: CodeWriter
1032 init(compiler: COMPILER)
1034 self.compiler = compiler
1035 self.writer = new CodeWriter(compiler.files.last)
1038 # Force to get the primitive class named `name
` or abort
1039 fun get_class(name: String): MClass do return self.compiler.mainmodule.get_primitive_class(name)
1041 # Force to get the primitive property named `name
` in the instance `recv
` or abort
1042 fun get_property(name: String, recv: MType): MMethod
1044 assert recv isa MClassType
1045 return self.compiler.modelbuilder.force_get_primitive_method(self.current_node.as(not null), name, recv.mclass, self.compiler.mainmodule)
1048 fun compile_callsite(callsite: CallSite, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1050 var initializers = callsite.mpropdef.initializers
1051 if not initializers.is_empty then
1052 var recv = arguments.first
1055 for p in initializers do
1056 if p isa MMethod then
1058 for x in p.intro.msignature.mparameters do
1059 args.add arguments[i]
1063 else if p isa MAttribute then
1064 self.write_attribute(p, recv, arguments[i])
1068 assert i == arguments.length
1070 return self.send(callsite.mproperty, [recv])
1073 return self.send(callsite.mproperty, arguments)
1076 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable is abstract
1078 fun calloc_array(ret_type: MType, arguments: Array[RuntimeVariable]) is abstract
1080 fun native_array_def(pname: String, ret_type: nullable MType, arguments: Array[RuntimeVariable]) is abstract
1082 # Transform varargs, in raw arguments, into a single argument of type `Array`
1083 # Note: this method modify the given `args
`
1084 # If there is no vararg, then `args
` is not modified.
1085 fun varargize(mpropdef: MPropDef, msignature: MSignature, args: Array[RuntimeVariable])
1087 var recv = args.first
1088 var vararg_rank = msignature.vararg_rank
1089 if vararg_rank >= 0 then
1090 assert args.length >= msignature.arity + 1 # because of self
1092 args = new Array[RuntimeVariable]
1094 args.add(rawargs.first) # recv
1096 for i in [0..vararg_rank[ do
1097 args.add(rawargs[i+1])
1100 var vararg_lastrank = vararg_rank + rawargs.length-1-msignature.arity
1101 var vararg = new Array[RuntimeVariable]
1102 for i in [vararg_rank..vararg_lastrank] do
1103 vararg.add(rawargs[i+1])
1106 var elttype = msignature.mparameters[vararg_rank].mtype
1107 args.add(self.vararg_instance(mpropdef, recv, vararg, elttype))
1109 for i in [vararg_lastrank+1..rawargs.length-1[ do
1110 args.add(rawargs[i+1])
1113 rawargs.add_all(args)
1119 # Anchor a type to the main module and the current receiver
1120 fun anchor(mtype: MType): MType
1122 if not mtype.need_anchor then return mtype
1123 return mtype.anchor_to(self.compiler.mainmodule, self.frame.receiver)
1126 fun resolve_for(mtype: MType, recv: RuntimeVariable): MType
1128 if not mtype.need_anchor then return mtype
1129 return mtype.resolve_for(recv.mcasttype, self.frame.receiver, self.compiler.mainmodule, true)
1132 # Unsafely cast a value to a new type
1133 # ie the result share the same C variable but my have a different mcasttype
1134 # NOTE: if the adaptation is useless then `value
` is returned as it.
1135 # ENSURE: `result
.name
== value
.name
`
1136 fun autoadapt(value: RuntimeVariable, mtype: MType): RuntimeVariable
1138 mtype = self.anchor(mtype)
1139 var valmtype = value.mcasttype
1140 if valmtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1144 if valmtype isa MNullableType and valmtype.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1145 var res = new RuntimeVariable(value.name, valmtype, valmtype.mtype)
1148 var res = new RuntimeVariable(value.name, valmtype, mtype)
1153 # Generate a super call from a method definition
1154 fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1156 # Adapt the arguments of a method according to targetted `MMethodDef`
1157 fun adapt_signature(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1159 # Unbox all the arguments of a method when implemented `extern` or `intern`
1160 fun unbox_signature_extern(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1162 # Box or unbox a value to another type iff a C type conversion is needed
1163 # ENSURE: `result
.mtype
.ctype
== mtype
.ctype
`
1164 fun autobox(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1166 # Box extern classes to be used in the generated code
1167 fun box_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1169 # Unbox extern classes to be used in extern code (legacy NI and FFI)
1170 fun unbox_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1172 # Generate a polymorphic subtype test
1173 fun type_test(value: RuntimeVariable, mtype: MType, tag: String): RuntimeVariable is abstract
1175 # Generate the code required to dynamically check if 2 objects share the same runtime type
1176 fun is_same_type_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1178 # Generate a Nit "is" for two runtime_variables
1179 fun equal_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1183 # Generate a static call on a method definition
1184 fun call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1186 # Generate a polymorphic send for the method `m
` and the arguments `args
`
1187 fun send(m: MMethod, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1189 # Generate a monomorphic send for the method `m
`, the type `t
` and the arguments `args
`
1190 fun monomorphic_send(m: MMethod, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1192 assert t isa MClassType
1193 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
1194 return self.call(propdef, t, args)
1197 # Generate a monomorphic super send from the method `m
`, the type `t
` and the arguments `args
`
1198 fun monomorphic_super_send(m: MMethodDef, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1200 assert t isa MClassType
1201 m = m.lookup_next_definition(self.compiler.mainmodule, t)
1202 return self.call(m, t, args)
1205 # Attributes handling
1207 # Generate a polymorphic attribute is_set test
1208 fun isset_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1210 # Generate a polymorphic attribute read
1211 fun read_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1213 # Generate a polymorphic attribute write
1214 fun write_attribute(a: MAttribute, recv: RuntimeVariable, value: RuntimeVariable) is abstract
1218 # Add a check and an abort for a null reciever if needed
1219 fun check_recv_notnull(recv: RuntimeVariable)
1221 if self.compiler.modelbuilder.toolcontext.opt_no_check_null.value then return
1223 var maybenull = recv.mcasttype isa MNullableType or recv.mcasttype isa MNullType
1225 self.add("if (unlikely({recv} == NULL)) \{")
1226 self.add_abort("Receiver is null")
1233 private var names: HashSet[String] = new HashSet[String]
1234 private var last: Int = 0
1236 # Return a new name based on `s
` and unique in the visitor
1237 fun get_name(s: String): String
1239 if not self.names.has(s) then
1243 var i = self.last + 1
1246 if not self.names.has(s2) then
1255 # Return an unique and stable identifier associated with an escapemark
1256 fun escapemark_name(e: nullable EscapeMark): String
1259 if escapemark_names.has_key(e) then return escapemark_names[e]
1261 if name == null then name = "label"
1262 name = get_name(name)
1263 escapemark_names[e] = name
1267 # Insert a C label for associated with an escapemark
1268 fun add_escape_label(e: nullable EscapeMark)
1270 if e == null then return
1271 if e.escapes.is_empty then return
1272 add("BREAK_{escapemark_name(e)}: (void)0;")
1275 private var escapemark_names = new HashMap[EscapeMark, String]
1277 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1278 # NOTE: we do not return a `RuntimeVariable` "NativeString" as the class may not exist in the module/program
1279 fun class_name_string(value: RuntimeVariable): String is abstract
1281 # Variables handling
1283 protected var variables: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
1285 # Return the local runtime_variable associated to a Nit local variable
1286 fun variable(variable: Variable): RuntimeVariable
1288 if self.variables.has_key(variable) then
1289 return self.variables[variable]
1291 var name = self.get_name("var_{variable.name}")
1292 var mtype = variable.declared_type.as(not null)
1293 mtype = self.anchor(mtype)
1294 var res = new RuntimeVariable(name, mtype, mtype)
1295 self.add_decl("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1296 self.variables[variable] = res
1301 # Return a new uninitialized local runtime_variable
1302 fun new_var(mtype: MType): RuntimeVariable
1304 mtype = self.anchor(mtype)
1305 var name = self.get_name("var")
1306 var res = new RuntimeVariable(name, mtype, mtype)
1307 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1311 # The difference with `new_var
` is the C static type of the local variable
1312 fun new_var_extern(mtype: MType): RuntimeVariable
1314 mtype = self.anchor(mtype)
1315 var name = self.get_name("var")
1316 var res = new RuntimeVariable(name, mtype, mtype)
1317 self.add_decl("{mtype.ctype_extern} {name} /* : {mtype} for extern */;")
1321 # Return a new uninitialized named runtime_variable
1322 fun new_named_var(mtype: MType, name: String): RuntimeVariable
1324 mtype = self.anchor(mtype)
1325 var res = new RuntimeVariable(name, mtype, mtype)
1326 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1330 # Correctly assign a left and a right value
1331 # Boxing and unboxing is performed if required
1332 fun assign(left, right: RuntimeVariable)
1334 right = self.autobox(right, left.mtype)
1335 self.add("{left} = {right};")
1338 # Generate instances
1340 # Generate a alloc-instance + init-attributes
1341 fun init_instance(mtype: MClassType): RuntimeVariable is abstract
1343 # Set a GC finalizer on `recv
`, only if `recv
` isa Finalizable
1344 fun set_finalizer(recv: RuntimeVariable)
1346 var mtype = recv.mtype
1347 var finalizable_type = compiler.mainmodule.finalizable_type
1348 if finalizable_type != null and not mtype.need_anchor and
1349 mtype.is_subtype(compiler.mainmodule, null, finalizable_type) then
1350 add "gc_register_finalizer({recv});"
1354 # Generate an integer value
1355 fun int_instance(value: Int): RuntimeVariable
1357 var res = self.new_var(self.get_class("Int").mclass_type)
1358 self.add("{res} = {value};")
1362 # Generate a string value
1363 fun string_instance(string: String): RuntimeVariable
1365 var mtype = self.get_class("String").mclass_type
1366 var name = self.get_name("varonce")
1367 self.add_decl("static {mtype.ctype} {name};")
1368 var res = self.new_var(mtype)
1369 self.add("if ({name}) \{")
1370 self.add("{res} = {name};")
1371 self.add("\} else \{")
1372 var native_mtype = self.get_class("NativeString").mclass_type
1373 var nat = self.new_var(native_mtype)
1374 self.add("{nat} = \"{string.escape_to_c}\";")
1375 var length = self.int_instance(string.length)
1376 self.add("{res} = {self.send(self.get_property("to_s_with_length", native_mtype), [nat, length]).as(not null)};")
1377 self.add("{name} = {res};")
1382 # Generate an array value
1383 fun array_instance(array: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1385 # Get an instance of a array for a vararg
1386 fun vararg_instance(mpropdef: MPropDef, recv: RuntimeVariable, varargs: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1390 # Add a line in the main part of the generated C
1391 fun add(s: String) do self.writer.lines.add(s)
1394 # (used for local or global declaration)
1395 fun add_decl(s: String) do self.writer.decl_lines.add(s)
1397 # Request the presence of a global declaration
1398 fun require_declaration(key: String)
1400 var reqs = self.writer.file.required_declarations
1401 if reqs.has(key) then return
1403 var node = current_node
1404 if node != null then compiler.requirers_of_declarations[key] = node
1407 # Add a declaration in the local-header
1408 # The declaration is ensured to be present once
1409 fun declare_once(s: String)
1411 self.compiler.provide_declaration(s, s)
1412 self.require_declaration(s)
1415 # look for a needed .h and .c file for a given .nit source-file
1416 # FIXME: bad API, parameter should be a `MModule`, not its source-file
1417 fun add_extern(file: String)
1419 file = file.strip_extension(".nit")
1420 var tryfile = file + ".nit.h"
1421 if tryfile.file_exists then
1422 self.declare_once("#include \"{tryfile.basename("")}\"")
1423 self.compiler.files_to_copy.add(tryfile)
1425 tryfile = file + "_nit.h"
1426 if tryfile.file_exists then
1427 self.declare_once("#include \"{tryfile.basename("")}\"")
1428 self.compiler.files_to_copy.add(tryfile)
1431 if self.compiler.seen_extern.has(file) then return
1432 self.compiler.seen_extern.add(file)
1433 tryfile = file + ".nit.c"
1434 if not tryfile.file_exists then
1435 tryfile = file + "_nit.c"
1436 if not tryfile.file_exists then return
1438 var f = new ExternCFile(tryfile.basename(""), "")
1439 self.compiler.extern_bodies.add(f)
1440 self.compiler.files_to_copy.add(tryfile)
1443 # Return a new local runtime_variable initialized with the C expression `cexpr
`.
1444 fun new_expr(cexpr: String, mtype: MType): RuntimeVariable
1446 var res = new_var(mtype)
1447 self.add("{res} = {cexpr};")
1451 # Generate generic abort
1452 # used by aborts, asserts, casts, etc.
1453 fun add_abort(message: String)
1455 self.add("PRINT_ERROR(\"Runtime error: %s\", \"{message.escape_to_c}\");")
1461 if self.current_node != null and self.current_node.location.file != null then
1462 self.add("PRINT_ERROR(\" (%s:%d)\\n\", \"{self.current_node.location.file.filename.escape_to_c}\", {current_node.location.line_start});")
1464 self.add("PRINT_ERROR(\"\\n\");")
1466 self.add("show_backtrace(1);")
1469 # Add a dynamic cast
1470 fun add_cast(value: RuntimeVariable, mtype: MType, tag: String)
1472 var res = self.type_test(value, mtype, tag)
1473 self.add("if (unlikely(!{res})) \{")
1474 var cn = self.class_name_string(value)
1475 self.add("PRINT_ERROR(\"Runtime error: Cast failed. Expected `%s
`, got `%s
`\", \"{mtype.to_s.escape_to_c}\", {cn});")
1480 # Generate a return with the value `s
`
1481 fun ret(s: RuntimeVariable)
1483 self.assign(self.frame.returnvar.as(not null), s)
1484 self.add("goto {self.frame.returnlabel.as(not null)};")
1487 # Compile a statement (if any)
1488 fun stmt(nexpr: nullable AExpr)
1490 if nexpr == null then return
1491 var old = self.current_node
1492 self.current_node = nexpr
1494 self.current_node = old
1497 # Compile an expression an return its result
1498 # `mtype
` is the expected return type, pass null if no specific type is expected.
1499 fun expr(nexpr: AExpr, mtype: nullable MType): RuntimeVariable
1501 var old = self.current_node
1502 self.current_node = nexpr
1503 var res = nexpr.expr(self).as(not null)
1504 if mtype != null then
1505 mtype = self.anchor(mtype)
1506 res = self.autobox(res, mtype)
1508 res = autoadapt(res, nexpr.mtype.as(not null))
1509 var implicit_cast_to = nexpr.implicit_cast_to
1510 if implicit_cast_to != null and not self.compiler.modelbuilder.toolcontext.opt_no_check_autocast.value then
1511 add_cast(res, implicit_cast_to, "auto")
1512 res = autoadapt(res, implicit_cast_to)
1514 self.current_node = old
1518 # Alias for `self.expr
(nexpr
, self.bool_type
)`
1519 fun expr_bool(nexpr: AExpr): RuntimeVariable do return expr(nexpr, bool_type)
1521 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1522 fun debug(message: String)
1524 var node = self.current_node
1525 if node == null then
1526 print "?: {message}"
1530 self.add("/* DEBUG: {message} */")
1534 # A C function associated to a Nit method
1535 # Because of customization, a given Nit method can be compiler more that once
1536 abstract class AbstractRuntimeFunction
1538 type COMPILER: AbstractCompiler
1539 type VISITOR: AbstractCompilerVisitor
1541 # The associated Nit method
1542 var mmethoddef: MMethodDef
1544 # The mangled c name of the runtime_function
1545 # Subclasses should redefine `build_c_name
` instead
1548 var res = self.c_name_cache
1549 if res != null then return res
1550 res = self.build_c_name
1551 self.c_name_cache = res
1555 # Non cached version of `c_name
`
1556 protected fun build_c_name: String is abstract
1558 protected var c_name_cache: nullable String = null is writable
1560 # Implements a call of the runtime_function
1561 # May inline the body or generate a C function call
1562 fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1564 # Generate the code for the `AbstractRuntimeFunction`
1565 # Warning: compile more than once compilation makes CC unhappy
1566 fun compile_to_c(compiler: COMPILER) is abstract
1569 # A runtime variable hold a runtime value in C.
1570 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
1572 # 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.
1573 class RuntimeVariable
1574 # The name of the variable in the C code
1577 # The static type of the variable (as declard in C)
1580 # The current casted type of the variable (as known in Nit)
1581 var mcasttype: MType is writable
1583 # If the variable exaclty a mcasttype?
1584 # false (usual value) means that the variable is a mcasttype or a subtype.
1585 var is_exact: Bool = false is writable
1587 init(name: String, mtype: MType, mcasttype: MType)
1591 self.mcasttype = mcasttype
1592 assert not mtype.need_anchor
1593 assert not mcasttype.need_anchor
1596 redef fun to_s do return name
1601 if self.is_exact then
1602 exact_str = " exact"
1607 if self.mtype == self.mcasttype then
1608 type_str = "{mtype}{exact_str}"
1610 type_str = "{mtype}({mcasttype}{exact_str})"
1612 return "<{name}:{type_str}>"
1616 # A frame correspond to a visited property in a `GlobalCompilerVisitor`
1619 type VISITOR: AbstractCompilerVisitor
1621 # The associated visitor
1622 var visitor: VISITOR
1624 # The executed property.
1625 # A Method in case of a call, an attribute in case of a default initialization.
1626 var mpropdef: MPropDef
1628 # The static type of the receiver
1629 var receiver: MClassType
1631 # Arguments of the method (the first is the receiver)
1632 var arguments: Array[RuntimeVariable]
1634 # The runtime_variable associated to the return (in a function)
1635 var returnvar: nullable RuntimeVariable = null is writable
1637 # The label at the end of the property
1638 var returnlabel: nullable String = null is writable
1642 # Return the C type associated to a given Nit static type
1643 fun ctype: String do return "val*"
1645 # C type outside of the compiler code and in boxes
1646 fun ctype_extern: String do return "val*"
1648 # Short name of the `ctype
` to use in unions
1649 fun ctypename: String do return "val"
1651 # Return the name of the C structure associated to a Nit live type
1652 fun c_name: String is abstract
1653 protected var c_name_cache: nullable String is protected writable
1656 redef class MClassType
1659 var res = self.c_name_cache
1660 if res != null then return res
1661 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
1662 self.c_name_cache = res
1666 redef fun ctype: String
1668 if mclass.name == "Int" then
1670 else if mclass.name == "Bool" then
1672 else if mclass.name == "Char" then
1674 else if mclass.name == "Float" then
1676 else if mclass.name == "NativeString" then
1678 else if mclass.name == "NativeArray" then
1685 redef fun ctype_extern: String
1687 if mclass.kind == extern_kind then
1694 redef fun ctypename: String
1696 if mclass.name == "Int" then
1698 else if mclass.name == "Bool" then
1700 else if mclass.name == "Char" then
1702 else if mclass.name == "Float" then
1704 else if mclass.name == "NativeString" then
1706 else if mclass.name == "NativeArray" then
1707 #return "{self.arguments.first.ctype}*"
1715 redef class MGenericType
1718 var res = self.c_name_cache
1719 if res != null then return res
1721 for t in self.arguments do
1722 res = res + t.c_name
1724 self.c_name_cache = res
1729 redef class MParameterType
1732 var res = self.c_name_cache
1733 if res != null then return res
1734 res = "{self.mclass.c_name}_FT{self.rank}"
1735 self.c_name_cache = res
1740 redef class MVirtualType
1743 var res = self.c_name_cache
1744 if res != null then return res
1745 res = "{self.mproperty.intro.mclassdef.mclass.c_name}_VT{self.mproperty.name}"
1746 self.c_name_cache = res
1751 redef class MNullableType
1754 var res = self.c_name_cache
1755 if res != null then return res
1756 res = "nullable_{self.mtype.c_name}"
1757 self.c_name_cache = res
1763 # Return the name of the C structure associated to a Nit class
1764 fun c_name: String do
1765 var res = self.c_name_cache
1766 if res != null then return res
1767 res = "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1768 self.c_name_cache = res
1771 private var c_name_cache: nullable String
1774 redef class MProperty
1775 fun c_name: String do
1776 var res = self.c_name_cache
1777 if res != null then return res
1778 res = "{self.intro.c_name}"
1779 self.c_name_cache = res
1782 private var c_name_cache: nullable String
1785 redef class MPropDef
1786 type VISITOR: AbstractCompilerVisitor
1788 private var c_name_cache: nullable String
1790 # The mangled name associated to the property
1793 var res = self.c_name_cache
1794 if res != null then return res
1795 res = "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1796 self.c_name_cache = res
1801 redef class MMethodDef
1802 # Can the body be inlined?
1803 fun can_inline(v: VISITOR): Bool
1805 if is_abstract then return true
1806 var modelbuilder = v.compiler.modelbuilder
1807 if modelbuilder.mpropdef2npropdef.has_key(self) then
1808 var npropdef = modelbuilder.mpropdef2npropdef[self]
1809 return npropdef.can_inline
1810 else if self.mproperty.name == "init" then
1811 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1818 # Inline the body in another visitor
1819 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1821 var modelbuilder = v.compiler.modelbuilder
1822 if modelbuilder.mpropdef2npropdef.has_key(self) then
1823 var npropdef = modelbuilder.mpropdef2npropdef[self]
1824 var oldnode = v.current_node
1825 v.current_node = npropdef
1826 self.compile_parameter_check(v, arguments)
1827 npropdef.compile_to_c(v, self, arguments)
1828 v.current_node = oldnode
1829 else if self.mproperty.name == "init" then
1830 var nclassdef = modelbuilder.mclassdef2nclassdef[self.mclassdef]
1831 var oldnode = v.current_node
1832 v.current_node = nclassdef
1833 self.compile_parameter_check(v, arguments)
1834 nclassdef.compile_to_c(v, self, arguments)
1835 v.current_node = oldnode
1842 # Generate type checks in the C code to check covariant parameters
1843 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1845 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1847 for i in [0..msignature.arity[ do
1848 # skip test for vararg since the array is instantiated with the correct polymorphic type
1849 if msignature.vararg_rank == i then continue
1851 # skip if the cast is not required
1852 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1853 if not origmtype.need_anchor then continue
1855 # get the parameter type
1856 var mtype = self.msignature.mparameters[i].mtype
1859 # note that v decides if and how to implements the cast
1860 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1861 v.add_cast(arguments[i+1], mtype, "covariance")
1868 redef class APropdef
1869 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1871 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1872 debug("Not yet implemented")
1875 fun can_inline: Bool do return true
1878 redef class AMethPropdef
1879 redef fun compile_to_c(v, mpropdef, arguments)
1881 if mpropdef.is_abstract then
1882 var cn = v.class_name_string(arguments.first)
1883 v.add("PRINT_ERROR(\"Runtime error: Abstract method `%s
` called on `%s
`\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1888 # Call the implicit super-init
1889 var auto_super_inits = self.auto_super_inits
1890 if auto_super_inits != null then
1891 var args = [arguments.first]
1892 for auto_super_init in auto_super_inits do
1893 assert auto_super_init.mproperty != mpropdef.mproperty
1895 for i in [0..auto_super_init.msignature.arity+1[ do
1896 args.add(arguments[i])
1898 assert auto_super_init.mproperty != mpropdef.mproperty
1899 v.compile_callsite(auto_super_init, args)
1902 if auto_super_call then
1903 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
1906 # Try special compilation
1907 if mpropdef.is_intern then
1908 if compile_intern_to_c(v, mpropdef, arguments) then return
1909 else if mpropdef.is_extern then
1910 if mpropdef.mproperty.is_init then
1911 if compile_externinit_to_c(v, mpropdef, arguments) then return
1913 if compile_externmeth_to_c(v, mpropdef, arguments) then return
1917 # Compile block if any
1918 var n_block = n_block
1919 if n_block != null then
1920 for i in [0..mpropdef.msignature.arity[ do
1921 var variable = self.n_signature.n_params[i].variable.as(not null)
1922 v.assign(v.variable(variable), arguments[i+1])
1929 var cn = v.class_name_string(arguments.first)
1930 v.add("PRINT_ERROR(\"Runtime error: uncompiled method `%s
` called on `%s
`. NOT YET IMPLEMENTED\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1934 redef fun can_inline
1936 if self.auto_super_inits != null then return false
1937 var nblock = self.n_block
1938 if nblock == null then return true
1939 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1940 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1944 fun compile_intern_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
1946 var pname = mpropdef.mproperty.name
1947 var cname = mpropdef.mclassdef.mclass.name
1948 var ret = mpropdef.msignature.return_mtype
1950 ret = v.resolve_for(ret, arguments.first)
1951 else if mpropdef.mproperty.is_new then
1952 ret = arguments.first.mcasttype
1954 if pname != "==" and pname != "!=" then
1955 v.adapt_signature(mpropdef, arguments)
1956 v.unbox_signature_extern(mpropdef, arguments)
1958 if cname == "Int" then
1959 if pname == "output" then
1960 v.add("printf(\"%ld\\n\", {arguments.first});")
1962 else if pname == "object_id" then
1963 v.ret(arguments.first)
1965 else if pname == "+" then
1966 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1968 else if pname == "-" then
1969 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1971 else if pname == "unary -" then
1972 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1974 else if pname == "*" then
1975 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1977 else if pname == "/" then
1978 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1980 else if pname == "%" then
1981 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1983 else if pname == "lshift" then
1984 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1986 else if pname == "rshift" then
1987 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1989 else if pname == "==" then
1990 v.ret(v.equal_test(arguments[0], arguments[1]))
1992 else if pname == "!=" then
1993 var res = v.equal_test(arguments[0], arguments[1])
1994 v.ret(v.new_expr("!{res}", ret.as(not null)))
1996 else if pname == "<" then
1997 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1999 else if pname == ">" then
2000 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
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 == "to_f" then
2009 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
2011 else if pname == "ascii" then
2012 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
2015 else if cname == "Char" then
2016 if pname == "output" then
2017 v.add("printf(\"%c\", {arguments.first});")
2019 else if pname == "object_id" then
2020 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2022 else if pname == "successor" then
2023 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
2025 else if pname == "predecessor" then
2026 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
2028 else if pname == "==" then
2029 v.ret(v.equal_test(arguments[0], arguments[1]))
2031 else if pname == "!=" then
2032 var res = v.equal_test(arguments[0], arguments[1])
2033 v.ret(v.new_expr("!{res}", ret.as(not null)))
2035 else if pname == "<" then
2036 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
2038 else if pname == ">" then
2039 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", 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 == "to_i" then
2048 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
2050 else if pname == "ascii" then
2051 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
2054 else if cname == "Bool" then
2055 if pname == "output" then
2056 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
2058 else if pname == "object_id" then
2059 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2061 else if pname == "==" then
2062 v.ret(v.equal_test(arguments[0], arguments[1]))
2064 else if pname == "!=" then
2065 var res = v.equal_test(arguments[0], arguments[1])
2066 v.ret(v.new_expr("!{res}", ret.as(not null)))
2069 else if cname == "Float" then
2070 if pname == "output" then
2071 v.add("printf(\"%f\\n\", {arguments.first});")
2073 else if pname == "object_id" then
2074 v.ret(v.new_expr("(double){arguments.first}", ret.as(not null)))
2076 else if pname == "+" then
2077 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
2079 else if pname == "-" then
2080 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
2082 else if pname == "unary -" then
2083 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
2085 else if pname == "succ" then
2086 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
2088 else if pname == "prec" then
2089 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
2091 else if pname == "*" then
2092 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
2094 else if pname == "/" then
2095 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
2097 else if pname == "==" then
2098 v.ret(v.equal_test(arguments[0], arguments[1]))
2100 else if pname == "!=" then
2101 var res = v.equal_test(arguments[0], arguments[1])
2102 v.ret(v.new_expr("!{res}", ret.as(not null)))
2104 else if pname == "<" then
2105 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
2107 else if pname == ">" then
2108 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
2110 else if pname == "<=" then
2111 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
2113 else if pname == ">=" then
2114 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
2116 else if pname == "to_i" then
2117 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
2120 else if cname == "NativeString" then
2121 if pname == "[]" then
2122 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
2124 else if pname == "[]=" then
2125 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2127 else if pname == "copy_to" then
2128 v.add("memmove({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2130 else if pname == "atoi" then
2131 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
2133 else if pname == "init" then
2134 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2137 else if cname == "NativeArray" then
2138 v.native_array_def(pname, ret, arguments)
2141 if pname == "exit" then
2142 v.add("exit({arguments[1]});")
2144 else if pname == "sys" then
2145 v.ret(v.new_expr("glob_sys", ret.as(not null)))
2147 else if pname == "calloc_string" then
2148 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2150 else if pname == "calloc_array" then
2151 v.calloc_array(ret.as(not null), arguments)
2153 else if pname == "object_id" then
2154 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2156 else if pname == "is_same_type" then
2157 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
2159 else if pname == "is_same_instance" then
2160 v.ret(v.equal_test(arguments[0], arguments[1]))
2162 else if pname == "output_class_name" then
2163 var nat = v.class_name_string(arguments.first)
2164 v.add("printf(\"%s\\n\", {nat});")
2166 else if pname == "native_class_name" then
2167 var nat = v.class_name_string(arguments.first)
2168 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
2170 else if pname == "force_garbage_collection" then
2171 v.add("nit_gcollect();")
2173 else if pname == "native_argc" then
2174 v.ret(v.new_expr("glob_argc", ret.as(not null)))
2176 else if pname == "native_argv" then
2177 v.ret(v.new_expr("glob_argv[{arguments[1]}]", ret.as(not null)))
2183 # Compile an extern method
2184 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2185 fun compile_externmeth_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 var res: nullable RuntimeVariable = null
2200 var ret = mpropdef.msignature.return_mtype
2202 ret = v.resolve_for(ret, arguments.first)
2203 res = v.new_var_extern(ret)
2205 v.adapt_signature(mpropdef, arguments)
2206 v.unbox_signature_extern(mpropdef, arguments)
2209 v.add("{externname}({arguments.join(", ")});")
2211 v.add("{res} = {externname}({arguments.join(", ")});")
2212 res = v.box_extern(res, ret.as(not null))
2218 # Compile an extern factory
2219 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2220 fun compile_externinit_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
2223 var at = self.get_single_annotation("extern", v.compiler.modelbuilder)
2225 externname = at.arg_as_string(v.compiler.modelbuilder)
2226 if externname == null then return false
2230 if location.file != null then
2231 var file = location.file.filename
2234 v.adapt_signature(mpropdef, arguments)
2235 v.unbox_signature_extern(mpropdef, arguments)
2236 var ret = arguments.first.mtype
2237 var res = v.new_var_extern(ret)
2241 v.add("{res} = {externname}({arguments.join(", ")});")
2242 res = v.box_extern(res, ret)
2248 redef class AAttrPropdef
2249 redef fun compile_to_c(v, mpropdef, arguments)
2251 if mpropdef == mreadpropdef then
2252 assert arguments.length == 1
2256 assert nexpr != null
2258 var ret = self.mpropdef.static_mtype
2259 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2260 var guard = self.mlazypropdef.mproperty
2262 set = v.isset_attribute(self.mpropdef.mproperty, arguments.first)
2264 set = v.read_attribute(guard, arguments.first)
2266 v.add("if(likely({set})) \{")
2267 res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
2269 var value = v.expr(nexpr, self.mpropdef.static_mtype)
2270 v.write_attribute(self.mpropdef.mproperty, arguments.first, value)
2271 v.assign(res, value)
2273 var true_v = v.new_expr("1", v.bool_type)
2274 v.write_attribute(guard, arguments.first, true_v)
2278 res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
2280 v.assign(v.frame.returnvar.as(not null), res)
2281 else if mpropdef == mwritepropdef then
2282 assert arguments.length == 2
2283 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
2285 var ret = self.mpropdef.static_mtype
2286 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2288 v.write_attribute(self.mlazypropdef.mproperty, arguments.first, v.new_expr("1", v.bool_type))
2296 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2298 var nexpr = self.n_expr
2299 if nexpr != null and not is_lazy then
2300 var oldnode = v.current_node
2301 v.current_node = self
2302 var old_frame = v.frame
2303 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
2305 var value = v.expr(nexpr, self.mpropdef.static_mtype)
2306 v.write_attribute(self.mpropdef.mproperty, recv, value)
2308 v.current_node = oldnode
2312 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2314 var nexpr = self.n_expr
2315 if nexpr != null then return
2317 var oldnode = v.current_node
2318 v.current_node = self
2319 var old_frame = v.frame
2320 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
2322 # Force read to check the initialization
2323 v.read_attribute(self.mpropdef.mproperty, recv)
2325 v.current_node = oldnode
2329 redef class AClassdef
2330 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
2332 if mpropdef == self.mfree_init then
2333 assert mpropdef.mproperty.is_root_init
2334 assert arguments.length == 1
2335 if not mpropdef.is_intro then
2336 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
2346 # Try to compile self as an expression
2347 # Do not call this method directly, use `v
.expr
` instead
2348 private fun expr(v: AbstractCompilerVisitor): nullable RuntimeVariable
2350 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\");")
2351 var mtype = self.mtype
2352 if mtype == null then
2355 var res = v.new_var(mtype)
2356 v.add("/* {res} = NOT YET {class_name} */")
2361 # Try to compile self as a statement
2362 # Do not call this method directly, use `v
.stmt
` instead
2363 private fun stmt(v: AbstractCompilerVisitor)
2366 if res != null then v.add("{res};")
2370 redef class ABlockExpr
2373 for e in self.n_expr do v.stmt(e)
2377 var last = self.n_expr.last
2378 for e in self.n_expr do
2379 if e == last then break
2382 return v.expr(last, null)
2386 redef class AVardeclExpr
2389 var variable = self.variable.as(not null)
2390 var ne = self.n_expr
2392 var i = v.expr(ne, variable.declared_type)
2393 v.assign(v.variable(variable), i)
2398 redef class AVarExpr
2401 var res = v.variable(self.variable.as(not null))
2402 var mtype = self.mtype.as(not null)
2403 return v.autoadapt(res, mtype)
2407 redef class AVarAssignExpr
2410 var variable = self.variable.as(not null)
2411 var i = v.expr(self.n_value, variable.declared_type)
2412 v.assign(v.variable(variable), i)
2416 var variable = self.variable.as(not null)
2417 var i = v.expr(self.n_value, variable.declared_type)
2418 v.assign(v.variable(variable), i)
2423 redef class AVarReassignExpr
2426 var variable = self.variable.as(not null)
2427 var vari = v.variable(variable)
2428 var value = v.expr(self.n_value, variable.declared_type)
2429 var res = v.compile_callsite(self.reassign_callsite.as(not null), [vari, value])
2431 v.assign(v.variable(variable), res)
2435 redef class ASelfExpr
2436 redef fun expr(v) do return v.frame.arguments.first
2439 redef class AEscapeExpr
2440 redef fun stmt(v) do v.add("goto BREAK_{v.escapemark_name(self.escapemark)};")
2443 redef class AReturnExpr
2446 var nexpr = self.n_expr
2447 if nexpr != null then
2448 var returnvar = v.frame.returnvar.as(not null)
2449 var i = v.expr(nexpr, returnvar.mtype)
2450 v.assign(returnvar, i)
2452 v.add("goto {v.frame.returnlabel.as(not null)};")
2456 redef class AAbortExpr
2457 redef fun stmt(v) do v.add_abort("Aborted")
2463 var cond = v.expr_bool(self.n_expr)
2464 v.add("if ({cond})\{")
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.as(not null), null))
2478 v.assign(res, v.expr(self.n_else.as(not null), null))
2484 redef class AIfexprExpr
2487 var res = v.new_var(self.mtype.as(not null))
2488 var cond = v.expr_bool(self.n_expr)
2489 v.add("if ({cond})\{")
2490 v.assign(res, v.expr(self.n_then, null))
2492 v.assign(res, v.expr(self.n_else, null))
2501 v.stmt(self.n_block)
2502 v.add_escape_label(break_mark)
2506 redef class AWhileExpr
2510 var cond = v.expr_bool(self.n_expr)
2511 v.add("if (!{cond}) break;")
2512 v.stmt(self.n_block)
2513 v.add_escape_label(continue_mark)
2515 v.add_escape_label(break_mark)
2519 redef class ALoopExpr
2523 v.stmt(self.n_block)
2524 v.add_escape_label(continue_mark)
2526 v.add_escape_label(break_mark)
2530 redef class AForExpr
2533 var cl = v.expr(self.n_expr, null)
2534 var it_meth = self.method_iterator
2535 assert it_meth != null
2536 var it = v.compile_callsite(it_meth, [cl])
2539 var isok_meth = self.method_is_ok
2540 assert isok_meth != null
2541 var ok = v.compile_callsite(isok_meth, [it])
2543 v.add("if(!{ok}) break;")
2544 if self.variables.length == 1 then
2545 var item_meth = self.method_item
2546 assert item_meth != null
2547 var i = v.compile_callsite(item_meth, [it])
2549 v.assign(v.variable(variables.first), i)
2550 else if self.variables.length == 2 then
2551 var key_meth = self.method_key
2552 assert key_meth != null
2553 var i = v.compile_callsite(key_meth, [it])
2555 v.assign(v.variable(variables[0]), i)
2556 var item_meth = self.method_item
2557 assert item_meth != null
2558 i = v.compile_callsite(item_meth, [it])
2560 v.assign(v.variable(variables[1]), i)
2564 v.stmt(self.n_block)
2565 v.add_escape_label(continue_mark)
2566 var next_meth = self.method_next
2567 assert next_meth != null
2568 v.compile_callsite(next_meth, [it])
2570 v.add_escape_label(break_mark)
2572 var method_finish = self.method_finish
2573 if method_finish != null then
2574 # TODO: Find a way to call this also in long escape (e.g. return)
2575 v.compile_callsite(method_finish, [it])
2580 redef class AAssertExpr
2583 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return
2585 var cond = v.expr_bool(self.n_expr)
2586 v.add("if (unlikely(!{cond})) \{")
2590 v.add_abort("Assert '{nid.text}' failed")
2592 v.add_abort("Assert failed")
2601 var res = v.new_var(self.mtype.as(not null))
2602 var i1 = v.expr_bool(self.n_expr)
2603 v.add("if ({i1}) \{")
2606 var i2 = v.expr_bool(self.n_expr2)
2607 v.add("{res} = {i2};")
2613 redef class AImpliesExpr
2616 var res = v.new_var(self.mtype.as(not null))
2617 var i1 = v.expr_bool(self.n_expr)
2618 v.add("if (!{i1}) \{")
2621 var i2 = v.expr_bool(self.n_expr2)
2622 v.add("{res} = {i2};")
2628 redef class AAndExpr
2631 var res = v.new_var(self.mtype.as(not null))
2632 var i1 = v.expr_bool(self.n_expr)
2633 v.add("if (!{i1}) \{")
2636 var i2 = v.expr_bool(self.n_expr2)
2637 v.add("{res} = {i2};")
2643 redef class ANotExpr
2646 var cond = v.expr_bool(self.n_expr)
2647 return v.new_expr("!{cond}", self.mtype.as(not null))
2651 redef class AOrElseExpr
2654 var res = v.new_var(self.mtype.as(not null))
2655 var i1 = v.expr(self.n_expr, null)
2656 v.add("if ({i1}!=NULL) \{")
2659 var i2 = v.expr(self.n_expr2, null)
2666 redef class AIntExpr
2667 redef fun expr(v) do return v.new_expr("{self.value.to_s}", self.mtype.as(not null))
2670 redef class AFloatExpr
2671 redef fun expr(v) do return v.new_expr("{self.n_float.text}", self.mtype.as(not null)) # FIXME use value, not n_float
2674 redef class ACharExpr
2675 redef fun expr(v) do return v.new_expr("'{self.value.to_s.escape_to_c}'", self.mtype.as(not null))
2678 redef class AArrayExpr
2681 var mtype = self.mtype.as(MClassType).arguments.first
2682 var array = new Array[RuntimeVariable]
2683 for nexpr in self.n_exprs.n_exprs do
2684 var i = v.expr(nexpr, mtype)
2687 return v.array_instance(array, mtype)
2691 redef class AStringFormExpr
2692 redef fun expr(v) do return v.string_instance(self.value.as(not null))
2695 redef class ASuperstringExpr
2698 var array = new Array[RuntimeVariable]
2699 for ne in self.n_exprs do
2700 if ne isa AStringFormExpr and ne.value == "" then continue # skip empty sub-strings
2701 var i = v.expr(ne, null)
2704 var a = v.array_instance(array, v.object_type)
2705 var res = v.send(v.get_property("to_s", a.mtype), [a])
2710 redef class ACrangeExpr
2713 var i1 = v.expr(self.n_expr, null)
2714 var i2 = v.expr(self.n_expr2, null)
2715 var mtype = self.mtype.as(MClassType)
2716 var res = v.init_instance(mtype)
2717 var it = v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2722 redef class AOrangeExpr
2725 var i1 = v.expr(self.n_expr, null)
2726 var i2 = v.expr(self.n_expr2, null)
2727 var mtype = self.mtype.as(MClassType)
2728 var res = v.init_instance(mtype)
2729 var it = v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2734 redef class ATrueExpr
2735 redef fun expr(v) do return v.new_expr("1", self.mtype.as(not null))
2738 redef class AFalseExpr
2739 redef fun expr(v) do return v.new_expr("0", self.mtype.as(not null))
2742 redef class ANullExpr
2743 redef fun expr(v) do return v.new_expr("NULL", self.mtype.as(not null))
2746 redef class AIsaExpr
2749 var i = v.expr(self.n_expr, null)
2750 return v.type_test(i, self.cast_type.as(not null), "isa")
2754 redef class AAsCastExpr
2757 var i = v.expr(self.n_expr, null)
2758 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2760 v.add_cast(i, self.mtype.as(not null), "as")
2765 redef class AAsNotnullExpr
2768 var i = v.expr(self.n_expr, null)
2769 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2771 if i.mtype.ctype != "val*" then return i
2773 v.add("if (unlikely({i} == NULL)) \{")
2774 v.add_abort("Cast failed")
2780 redef class AParExpr
2781 redef fun expr(v) do return v.expr(self.n_expr, null)
2784 redef class AOnceExpr
2787 var mtype = self.mtype.as(not null)
2788 var name = v.get_name("varonce")
2789 var guard = v.get_name(name + "_guard")
2790 v.add_decl("static {mtype.ctype} {name};")
2791 v.add_decl("static int {guard};")
2792 var res = v.new_var(mtype)
2793 v.add("if ({guard}) \{")
2794 v.add("{res} = {name};")
2796 var i = v.expr(self.n_expr, mtype)
2797 v.add("{res} = {i};")
2798 v.add("{name} = {res};")
2799 v.add("{guard} = 1;")
2805 redef class ASendExpr
2808 var recv = v.expr(self.n_expr, null)
2810 for a in self.raw_arguments do
2811 args.add(v.expr(a, null))
2813 return v.compile_callsite(self.callsite.as(not null), args)
2817 redef class ASendReassignFormExpr
2820 var recv = v.expr(self.n_expr, null)
2822 for a in self.raw_arguments do
2823 args.add(v.expr(a, null))
2825 var value = v.expr(self.n_value, null)
2827 var left = v.compile_callsite(self.callsite.as(not null), args)
2830 var res = v.compile_callsite(self.reassign_callsite.as(not null), [left, value])
2834 v.compile_callsite(self.write_callsite.as(not null), args)
2838 redef class ASuperExpr
2841 var recv = v.frame.arguments.first
2843 for a in self.n_args.n_exprs do
2844 args.add(v.expr(a, null))
2847 var callsite = self.callsite
2848 if callsite != null then
2849 # Add additionnals arguments for the super init call
2850 if args.length == 1 then
2851 for i in [0..callsite.msignature.arity[ do
2852 args.add(v.frame.arguments[i+1])
2856 var res = v.compile_callsite(callsite, args)
2860 if args.length == 1 then
2861 args = v.frame.arguments
2864 # stantard call-next-method
2865 return v.supercall(mpropdef.as(not null), recv.mtype.as(MClassType), args)
2869 redef class ANewExpr
2872 var mtype = self.mtype.as(MClassType)
2874 var ctype = mtype.ctype
2875 if mtype.mclass.name == "NativeArray" then
2876 assert self.n_args.n_exprs.length == 1
2877 var l = v.expr(self.n_args.n_exprs.first, null)
2878 assert mtype isa MGenericType
2879 var elttype = mtype.arguments.first
2880 return v.native_array_instance(elttype, l)
2881 else if ctype == "val*" then
2882 recv = v.init_instance(mtype)
2883 else if ctype == "char*" then
2884 recv = v.new_expr("NULL/*special!*/", mtype)
2886 recv = v.new_expr("({ctype})0/*special!*/", mtype)
2889 for a in self.n_args.n_exprs do
2890 args.add(v.expr(a, null))
2892 var res2 = v.compile_callsite(self.callsite.as(not null), args)
2893 if res2 != null then
2894 #self.debug("got {res2} from {mproperty}. drop {recv}")
2901 redef class AAttrExpr
2904 var recv = v.expr(self.n_expr, null)
2905 var mproperty = self.mproperty.as(not null)
2906 return v.read_attribute(mproperty, recv)
2910 redef class AAttrAssignExpr
2913 var recv = v.expr(self.n_expr, null)
2914 var i = v.expr(self.n_value, null)
2915 var mproperty = self.mproperty.as(not null)
2916 v.write_attribute(mproperty, recv, i)
2920 redef class AAttrReassignExpr
2923 var recv = v.expr(self.n_expr, null)
2924 var value = v.expr(self.n_value, null)
2925 var mproperty = self.mproperty.as(not null)
2926 var attr = v.read_attribute(mproperty, recv)
2927 var res = v.compile_callsite(self.reassign_callsite.as(not null), [attr, value])
2929 v.write_attribute(mproperty, recv, res)
2933 redef class AIssetAttrExpr
2936 var recv = v.expr(self.n_expr, null)
2937 var mproperty = self.mproperty.as(not null)
2938 return v.isset_attribute(mproperty, recv)
2942 redef class ADebugTypeExpr
2951 redef class Array[E]
2952 # Return a new `Array` with the elements only contened in self and not in `o
`
2953 fun -(o: Array[E]): Array[E] do
2954 var res = new Array[E]
2955 for e in self do if not o.has(e) then res.add(e)
2961 # All `MProperty` associated to all `MClassDef` of `mclass
`
2962 fun properties(mclass: MClass): Set[MProperty] do
2963 if not self.properties_cache.has_key(mclass) then
2964 var properties = new HashSet[MProperty]
2965 var parents = new Array[MClass]
2966 if self.flatten_mclass_hierarchy.has(mclass) then
2967 parents.add_all(mclass.in_hierarchy(self).direct_greaters)
2969 for parent in parents do
2970 properties.add_all(self.properties(parent))
2972 for mclassdef in mclass.mclassdefs do
2973 if not self.in_importation <= mclassdef.mmodule then continue
2974 for mprop in mclassdef.intro_mproperties do
2975 properties.add(mprop)
2978 self.properties_cache[mclass] = properties
2980 return properties_cache[mclass]
2982 private var properties_cache: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
2984 # Write FFI and nitni results to file
2985 fun finalize_ffi(c: AbstractCompiler) do end
2987 # Give requided addinional system libraries (as given to LD_LIBS)
2988 # Note: can return null instead of an empty set
2989 fun collect_linker_libs: nullable Set[String] do return null
2992 # Create a tool context to handle options and paths
2993 var toolcontext = new ToolContext
2995 var opt_mixins = new OptionArray("Additionals module to min-in", "-m")
2996 toolcontext.option_context.add_option(opt_mixins)
2998 toolcontext.tooldescription = "Usage: nitg [OPTION]... file.nit...\nCompiles Nit programs."
3000 # We do not add other options, so process them now!
3001 toolcontext.process_options(args)
3003 # We need a model to collect stufs
3004 var model = new Model
3005 # An a model builder to parse files
3006 var modelbuilder = new ModelBuilder(model, toolcontext)
3008 var arguments = toolcontext.option_context.rest
3009 if arguments.length > 1 and toolcontext.opt_output.value != null then
3010 print "Error: --output needs a single source file. Do you prefer --dir?"
3014 # Here we load an process all modules passed on the command line
3015 var mmodules = modelbuilder.parse(arguments)
3016 var mixins = modelbuilder.parse(opt_mixins.value)
3018 if mmodules.is_empty then return
3019 modelbuilder.run_phases
3021 for mmodule in mmodules do
3022 toolcontext.info("*** PROCESS {mmodule} ***", 1)
3024 if not mixins.is_empty then
3027 toolcontext.run_global_phases(ms)