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
28 private import explain_assert_api
30 # Add compiling options
31 redef class ToolContext
33 var opt_output
= new OptionString("Filename of the generated executable", "-o", "--output")
35 var opt_dir
= new OptionString("Output directory", "--dir")
37 var opt_run
= new OptionBool("Execute the binary after the compilation", "--run")
39 var opt_no_cc
= new OptionBool("Do not invoke the C compiler", "--no-cc")
41 var opt_no_main
= new OptionBool("Do not generate main entry point", "--no-main")
43 var opt_make_flags
= new OptionString("Additional options to the `make` command", "--make-flags")
45 var opt_max_c_lines
= new OptionInt("Maximum number of lines in generated C files. Use 0 for unlimited", 10000, "--max-c-lines")
47 var opt_group_c_files
= new OptionBool("Group all generated code in the same series of files", "--group-c-files")
49 var opt_compile_dir
= new OptionString("Directory used to generate temporary files", "--compile-dir")
51 var opt_hardening
= new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
52 # --no-check-covariance
53 var opt_no_check_covariance
= new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
54 # --no-check-attr-isset
55 var opt_no_check_attr_isset
= new OptionBool("Disable isset tests before each attribute access (dangerous)", "--no-check-attr-isset")
57 var opt_no_check_assert
= new OptionBool("Disable the evaluation of explicit `assert` and `as` (dangerous)", "--no-check-assert")
59 var opt_no_check_autocast
= new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
61 var opt_no_check_null
= new OptionBool("Disable tests of null receiver (dangerous)", "--no-check-null")
63 var opt_no_check_all
= new OptionBool("Disable all tests (dangerous)", "--no-check-all")
64 # --typing-test-metrics
65 var opt_typing_test_metrics
= new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
66 # --invocation-metrics
67 var opt_invocation_metrics
= new OptionBool("Enable static and dynamic count of all method invocations", "--invocation-metrics")
68 # --isset-checks-metrics
69 var opt_isset_checks_metrics
= new OptionBool("Enable static and dynamic count of isset checks before attributes access", "--isset-checks-metrics")
71 var opt_no_stacktrace
= new OptionBool("Disable the generation of stack traces", "--no-stacktrace")
73 var opt_no_gcc_directive
= new OptionArray("Disable advanced gcc directives for optimization", "--no-gcc-directive")
75 var opt_release
= new OptionBool("Compile in release mode and finalize application", "--release")
77 var opt_debug
= new OptionBool("Compile in debug mode (no C-side optimization)", "-g", "--debug")
82 self.option_context
.add_option
(self.opt_output
, self.opt_dir
, self.opt_run
, self.opt_no_cc
, self.opt_no_main
, self.opt_make_flags
, self.opt_compile_dir
, self.opt_hardening
)
83 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
)
84 self.option_context
.add_option
(self.opt_typing_test_metrics
, self.opt_invocation_metrics
, self.opt_isset_checks_metrics
)
85 self.option_context
.add_option
(self.opt_no_stacktrace
)
86 self.option_context
.add_option
(self.opt_no_gcc_directive
)
87 self.option_context
.add_option
(self.opt_release
)
88 self.option_context
.add_option
(self.opt_max_c_lines
, self.opt_group_c_files
)
89 self.option_context
.add_option
(self.opt_debug
)
91 opt_no_main
.hidden
= true
94 redef fun process_options
(args
)
98 if opt_output
.value
!= null and opt_dir
.value
!= null then
99 print
"Option Error: cannot use both --dir and --output"
103 if opt_no_check_all
.value
then
104 opt_no_check_covariance
.value
= true
105 opt_no_check_attr_isset
.value
= true
106 opt_no_check_assert
.value
= true
107 opt_no_check_autocast
.value
= true
108 opt_no_check_null
.value
= true
113 redef class ModelBuilder
114 # Simple indirection to `Toolchain::write_and_make`
115 protected fun write_and_make
(compiler
: AbstractCompiler)
117 var platform
= compiler
.target_platform
118 var toolchain
= platform
.toolchain
(toolcontext
, compiler
)
119 compiler
.toolchain
= toolchain
120 toolchain
.write_and_make
125 # The specific tool-chain associated to the platform
126 fun toolchain
(toolcontext
: ToolContext, compiler
: AbstractCompiler): Toolchain
128 return new MakefileToolchain(toolcontext
, compiler
)
132 # Build toolchain for a specific target program, varies per `Platform`
136 var toolcontext
: ToolContext
138 # Compiler of the target program
139 var compiler
: AbstractCompiler
141 # Directory where to generate all files
143 # The option `--compile_dir` change this directory.
144 fun root_compile_dir
: String
146 var compile_dir
= toolcontext
.opt_compile_dir
.value
147 if compile_dir
== null then compile_dir
= "nit_compile"
151 # Directory where to generate all C files
153 # By default it is `root_compile_dir` but some platform may require that it is a subdirectory.
154 fun compile_dir
: String do return root_compile_dir
156 # Write all C files and compile them
157 fun write_and_make
is abstract
160 # Default toolchain using a Makefile
161 class MakefileToolchain
164 redef fun write_and_make
166 var debug
= toolcontext
.opt_debug
.value
167 var compile_dir
= compile_dir
169 # Remove the compilation directory unless explicitly set
170 var auto_remove
= toolcontext
.opt_compile_dir
.value
== null
171 # If debug flag is set, do not remove sources
172 if debug
then auto_remove
= false
174 # Generate the .h and .c files
175 # A single C file regroups many compiled rumtime functions
176 # 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
178 self.toolcontext
.info
("*** WRITING C ***", 1)
180 root_compile_dir
.mkdir
183 var cfiles
= new Array[String]
184 write_files
(compile_dir
, cfiles
)
186 # Generate the Makefile
188 write_makefile
(compile_dir
, cfiles
)
191 self.toolcontext
.info
("*** END WRITING C: {time1-time0} ***", 2)
193 if not toolcontext
.check_errors
then return
195 # Execute the Makefile
197 if self.toolcontext
.opt_no_cc
.value
then return
200 self.toolcontext
.info
("*** COMPILING C ***", 1)
202 compile_c_code
(compile_dir
)
205 sys
.system
("rm -r -- '{root_compile_dir.escape_to_sh}/'")
208 if toolcontext
.opt_run
.value
then
209 var mainmodule
= compiler
.mainmodule
210 var out
= outfile
(mainmodule
)
212 cmd
.append toolcontext
.option_context
.rest
213 toolcontext
.exec_and_check
(cmd
, "--run")
217 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
220 # Write all source files to the `compile_dir`
221 fun write_files
(compile_dir
: String, cfiles
: Array[String])
223 var platform
= compiler
.target_platform
224 if platform
.supports_libunwind
then compiler
.build_c_to_nit_bindings
225 var cc_opt_with_libgc
= "-DWITH_LIBGC"
226 if not platform
.supports_libgc
then cc_opt_with_libgc
= ""
228 # Add gc_choser.h to aditionnal bodies
229 var gc_chooser
= new ExternCFile("gc_chooser.c", cc_opt_with_libgc
)
230 if cc_opt_with_libgc
!= "" then gc_chooser
.pkgconfigs
.add
"bdw-gc"
231 compiler
.extern_bodies
.add
(gc_chooser
)
232 var clib
= toolcontext
.nit_dir
/ "clib"
233 compiler
.files_to_copy
.add
"{clib}/gc_chooser.c"
234 compiler
.files_to_copy
.add
"{clib}/gc_chooser.h"
237 for m
in compiler
.mainmodule
.in_importation
.greaters
do
238 compiler
.finalize_ffi_for_module
(m
)
241 # Copy original .[ch] files to compile_dir
242 for src
in compiler
.files_to_copy
do
243 var basename
= src
.basename
244 var dst
= "{compile_dir}/{basename}"
248 var hfilename
= compiler
.header
.file
.name
+ ".h"
249 var hfilepath
= "{compile_dir}/{hfilename}"
250 var h
= new FileWriter.open
(hfilepath
)
251 for l
in compiler
.header
.decl_lines
do
255 for l
in compiler
.header
.lines
do
261 var max_c_lines
= toolcontext
.opt_max_c_lines
.value
262 for f
in compiler
.files
do
265 var file
: nullable FileWriter = null
266 for vis
in f
.writers
do
267 if vis
== compiler
.header
then continue
268 var total_lines
= vis
.lines
.length
+ vis
.decl_lines
.length
269 if total_lines
== 0 then continue
271 if file
== null or (count
> max_c_lines
and max_c_lines
> 0) then
273 if file
!= null then file
.close
274 var cfilename
= "{f.name}.{i}.c"
275 var cfilepath
= "{compile_dir}/{cfilename}"
276 self.toolcontext
.info
("new C source files to compile: {cfilepath}", 3)
277 cfiles
.add
(cfilename
)
278 file
= new FileWriter.open
(cfilepath
)
279 file
.write
"#include \"{f.name}.0.h\
"\n"
282 for l
in vis
.decl_lines
do
286 for l
in vis
.lines
do
291 if file
== null then continue
294 var cfilename
= "{f.name}.0.h"
295 var cfilepath
= "{compile_dir}/{cfilename}"
296 var hfile
: nullable FileWriter = null
297 hfile
= new FileWriter.open
(cfilepath
)
298 hfile
.write
"#include \"{hfilename}\
"\n"
299 for key
in f
.required_declarations
do
300 if not compiler
.provided_declarations
.has_key
(key
) then
301 var node
= compiler
.requirers_of_declarations
.get_or_null
(key
)
303 node
.debug
"No provided declaration for {key}"
305 print
"No provided declaration for {key}"
309 hfile
.write compiler
.provided_declarations
[key
]
315 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
318 # Get the name of the Makefile to use
319 fun makefile_name
: String do return "{compiler.mainmodule.c_name}.mk"
321 # Get the default name of the executable to produce
322 fun default_outname
: String
324 var mainmodule
= compiler
.mainmodule
.first_real_mmodule
325 return mainmodule
.name
328 # Combine options and platform informations to get the final path of the outfile
329 fun outfile
(mainmodule
: MModule): String
331 var res
= self.toolcontext
.opt_output
.value
332 if res
!= null then return res
333 res
= default_outname
334 var dir
= self.toolcontext
.opt_dir
.value
335 if dir
!= null then return dir
.join_path
(res
)
340 fun write_makefile
(compile_dir
: String, cfiles
: Array[String])
342 var mainmodule
= compiler
.mainmodule
343 var platform
= compiler
.target_platform
345 var outname
= outfile
(mainmodule
)
347 var real_outpath
= compile_dir
.relpath
(outname
)
348 var outpath
= real_outpath
.escape_to_mk
349 if outpath
!= real_outpath
then
350 # If the name is crazy and need escaping, we will do an indirection
351 # 1. generate the binary in the nit_compile dir under an escaped name
352 # 2. copy the binary at the right place in the `all` goal.
353 outpath
= mainmodule
.c_name
355 var makename
= makefile_name
356 var makepath
= "{compile_dir}/{makename}"
357 var makefile
= new FileWriter.open
(makepath
)
359 var linker_options
= new HashSet[String]
360 for m
in mainmodule
.in_importation
.greaters
do
361 var libs
= m
.collect_linker_libs
362 if libs
!= null then linker_options
.add_all
(libs
)
364 var debug
= toolcontext
.opt_debug
.value
367 ifeq ($(origin CC), default)
370 ifeq ($(origin CXX), default)
373 CFLAGS ?= -g {{{if not debug then "-O2" else ""}}} -Wno-unused-value -Wno-switch -Wno-attributes -Wno-trigraphs
376 LDLIBS ?= -lm {{{linker_options.join(" ")}}}
379 makefile
.write
"\n# SPECIAL CONFIGURATION FLAGS\n"
380 if platform
.supports_libunwind
then
381 if toolcontext
.opt_no_stacktrace
.value
then
382 makefile
.write
"NO_STACKTRACE ?= True"
384 makefile
.write
"NO_STACKTRACE ?= # Set to `True` to enable"
388 # Dynamic adaptations
389 # While `platform` enable complex toolchains, they are statically applied
390 # For a dynamic adaptsation of the compilation, the generated Makefile should check and adapt things itself
391 makefile
.write
"\n\n"
393 # Check and adapt the targeted system
394 makefile
.write
("uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n")
396 # Check and adapt for the compiler used
397 # clang need an additionnal `-Qunused-arguments`
398 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")
400 if platform
.supports_libunwind
then
402 ifneq ($(NO_STACKTRACE), True)
403 # Check and include lib-unwind in a portable way
404 ifneq ($(uname_S),Darwin)
405 # already included on macosx, but need to get the correct flags in other supported platforms.
406 ifeq ($(shell pkg-config --exists 'libunwind'; echo $$?), 0)
407 LDLIBS += `pkg-config --libs libunwind`
408 CFLAGS += `pkg-config --cflags libunwind`
410 $(warning "[_] stack-traces disabled. Please install libunwind-dev.")
411 CFLAGS += -D NO_STACKTRACE
415 # Stacktraces disabled
416 CFLAGS += -D NO_STACKTRACE
421 makefile
.write
("CFLAGS += -D NO_STACKTRACE\n\n")
425 # Special configuration for Darwin
426 ifeq ($(uname_S),Darwin)
427 # Remove POSIX flag -lrt
428 LDLIBS := $(filter-out -lrt,$(LDLIBS))
431 # Special configuration for Windows under mingw64
432 ifneq ($(findstring MINGW64,$(uname_S)),)
433 # Use the pcreposix regex library
434 LDLIBS += -lpcreposix
436 # Remove POSIX flag -lrt
437 LDLIBS := $(filter-out -lrt,$(LDLIBS))
439 # Silence warnings when storing Int, Char and Bool as pointer address
440 CFLAGS += -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast
445 makefile
.write
("all: {outpath}\n")
446 if outpath
!= real_outpath
then
447 makefile
.write
("\tcp -- {outpath.escape_to_sh} {real_outpath.escape_to_sh.replace("$","$$")}")
451 var ofiles
= new Array[String]
452 var dep_rules
= new Array[String]
453 # Compile each generated file
455 var o
= f
.strip_extension
(".c") + ".o"
456 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) $(CINCL) -c -o {o} {f}\n\n")
461 # Generate linker script, if any
462 if not compiler
.linker_script
.is_empty
then
463 var linker_script_path
= "{compile_dir}/linker_script"
464 ofiles
.add
"linker_script"
465 var f
= new FileWriter.open
(linker_script_path
)
466 for l
in compiler
.linker_script
do
473 # pkg-config annotation support
474 var pkgconfigs
= new Array[String]
475 for f
in compiler
.extern_bodies
do
476 pkgconfigs
.add_all f
.pkgconfigs
479 # Only test if pkg-config is used
480 if not pkgconfigs
.is_empty
then
482 # Check availability of pkg-config, silence the proc output
483 toolcontext
.check_pkgconfig_packages pkgconfigs
485 # Double the check in the Makefile in case it's distributed
487 # does pkg-config exists?
488 ifneq ($(shell which pkg-config >/dev/null; echo $$?), 0)
489 $(error "Command `pkg-config` not found. Please install it")
492 for p
in pkgconfigs
do
494 # Check for library {{{p}}}
495 ifneq ($(shell pkg-config --exists '{{{p}}}'; echo $$?), 0)
496 $(error "pkg-config: package {{{p}}} is not found.")
502 # Compile each required extern body into a specific .o
503 var java_files
= new Array[ExternFile]
504 for f
in compiler
.extern_bodies
do
505 var o
= f
.makefile_rule_name
506 var ff
= f
.filename
.basename
507 makefile
.write
("{o}: {ff}\n")
508 makefile
.write
("\t{f.makefile_rule_content}\n\n")
509 dep_rules
.add
(f
.makefile_rule_name
)
511 if f
.compiles_to_o_file
then ofiles
.add
(o
)
512 if f
.add_to_jar
then java_files
.add
(f
)
515 if not java_files
.is_empty
then
516 var jar_file
= "{outpath}.jar"
518 var class_files_array
= new Array[String]
519 for f
in java_files
do class_files_array
.add
(f
.makefile_rule_name
)
520 var class_files
= class_files_array
.join
(" ")
522 makefile
.write
("{jar_file}: {class_files}\n")
523 makefile
.write
("\tjar cf {jar_file} {class_files}\n\n")
524 dep_rules
.add jar_file
529 if not pkgconfigs
.is_empty
then
530 pkg
= "`pkg-config --libs {pkgconfigs.join(" ")}`"
532 makefile
.write
("{outpath}: {dep_rules.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outpath.escape_to_sh} {ofiles.join(" ")} $(LDLIBS) {pkg}\n\n")
534 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n")
535 if outpath
!= real_outpath
then
536 makefile
.write
("\trm -- {outpath.escape_to_sh} 2>/dev/null\n")
539 self.toolcontext
.info
("Generated makefile: {makepath}", 2)
541 makepath
.file_copy_to
"{compile_dir}/Makefile"
544 # The C code is generated, compile it to an executable
545 fun compile_c_code
(compile_dir
: String)
547 var makename
= makefile_name
549 var makeflags
= self.toolcontext
.opt_make_flags
.value
550 if makeflags
== null then makeflags
= ""
552 var command
= "make -B -C {compile_dir} -f {makename} -j 4 {makeflags}"
553 self.toolcontext
.info
(command
, 2)
556 if self.toolcontext
.verbose_level
>= 3 then
557 res
= sys
.system
("{command} 2>&1")
558 else if is_windows
then
559 res
= sys
.system
("{command} 2>&1 >nul")
561 res
= sys
.system
("{command} 2>&1 >/dev/null")
564 toolcontext
.error
(null, "Compilation Error: `make` failed with error code: {res}. The command was `{command}`.")
569 # Singleton that store the knowledge about the compilation process
570 abstract class AbstractCompiler
571 type VISITOR: AbstractCompilerVisitor
573 # Table corresponding c_names to nit names (methods)
574 var names
= new HashMap[String, String]
576 # The main module of the program currently compiled
577 # Is assigned during the separate compilation
578 var mainmodule
: MModule is writable
580 # The real main module of the program
581 var realmainmodule
: MModule is noinit
583 # The modelbuilder used to know the model and the AST
584 var modelbuilder
: ModelBuilder is protected writable
586 # The associated toolchain
588 # Set by `modelbuilder.write_and_make` and permit sub-routines to access the current toolchain if required.
589 var toolchain
: Toolchain is noinit
591 # Is hardening asked? (see --hardening)
592 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
594 # The targeted specific platform
595 var target_platform
: Platform is noinit
599 self.realmainmodule
= mainmodule
600 target_platform
= mainmodule
.target_platform
or else new Platform
603 # Do the full code generation of the program `mainmodule`
604 # It is the main method usually called after the instantiation
605 fun do_compilation
is abstract
607 # Force the creation of a new file
608 # The point is to avoid contamination between must-be-compiled-separately files
609 fun new_file
(name
: String): CodeFile
611 if modelbuilder
.toolcontext
.opt_group_c_files
.value
then
612 if self.files
.is_empty
then
613 var f
= new CodeFile(mainmodule
.c_name
)
616 return self.files
.first
618 var f
= new CodeFile(name
)
623 # The list of all associated files
624 # Used to generate .c files
625 var files
= new Array[CodeFile]
627 # Initialize a visitor specific for a compiler engine
628 fun new_visitor
: VISITOR is abstract
630 # Where global declaration are stored (the main .h)
631 var header
: CodeWriter is writable, noinit
633 # Additionnal linker script for `ld`.
634 # Mainly used to do specific link-time symbol resolution
635 var linker_script
= new Array[String]
637 # Provide a declaration that can be requested (before or latter) by a visitor
638 fun provide_declaration
(key
: String, s
: String)
640 if self.provided_declarations
.has_key
(key
) then
641 assert self.provided_declarations
[key
] == s
643 self.provided_declarations
[key
] = s
646 private var provided_declarations
= new HashMap[String, String]
648 private var requirers_of_declarations
= new HashMap[String, ANode]
650 # Builds the .c and .h files to be used when generating a Stack Trace
651 # Binds the generated C function names to Nit function names
652 fun build_c_to_nit_bindings
654 var compile_dir
= toolchain
.compile_dir
656 var stream
= new FileWriter.open
("{compile_dir}/c_functions_hash.c")
657 stream
.write
("#include <string.h>\n")
658 stream
.write
("#include <stdlib.h>\n")
659 stream
.write
("#include \"c_functions_hash
.h\
"\n")
660 stream
.write
("typedef struct C_Nit_Names\{char* name; char* nit_name;\}C_Nit_Names;\n")
661 stream
.write
("const char* get_nit_name(register const char* procproc, register unsigned int len)\{\n")
662 stream
.write
("char* procname = malloc(len+1);")
663 stream
.write
("memcpy(procname, procproc, len);")
664 stream
.write
("procname[len] = '\\0';")
665 stream
.write
("static const C_Nit_Names map[{names.length}] = \{\n")
666 for i
in names
.keys
do
668 stream.write(i.escape_to_c)
669 stream.write("\
",\"")
670 stream.write(names[i].escape_to_c)
671 stream.write("\
"\},\n")
673 stream
.write
("\};\n")
674 stream
.write
("int i;")
675 stream
.write
("for(i = 0; i < {names.length}; i++)\{")
676 stream
.write
("if(strcmp(procname,map[i].name) == 0)\{")
677 stream
.write
("free(procname);")
678 stream
.write
("return map[i].nit_name;")
681 stream
.write
("free(procname);")
682 stream
.write
("return NULL;")
686 stream
= new FileWriter.open
("{compile_dir}/c_functions_hash.h")
687 stream
.write
("const char* get_nit_name(register const char* procname, register unsigned int len);\n")
690 extern_bodies
.add
(new ExternCFile("{compile_dir}/c_functions_hash.c", ""))
694 # This method call compile_header_strucs method that has to be refined
695 fun compile_header
do
696 self.header
.add_decl
("#include <stdlib.h>")
697 self.header
.add_decl
("#include <stdio.h>")
698 self.header
.add_decl
("#include <string.h>")
700 self.header
.add_decl
("#include <setjmp.h>\n")
701 self.header
.add_decl
("#include <sys/types.h>\n")
702 self.header
.add_decl
("#include <unistd.h>\n")
703 self.header
.add_decl
("#include <stdint.h>\n")
704 self.header
.add_decl
("#ifdef __linux__")
705 self.header
.add_decl
(" #include <endian.h>")
706 self.header
.add_decl
("#endif")
707 self.header
.add_decl
("#include <inttypes.h>\n")
708 self.header
.add_decl
("#include \"gc_chooser
.h\
"")
709 self.header
.add_decl
("#ifdef __APPLE__")
710 self.header
.add_decl
(" #include <TargetConditionals.h>")
711 self.header
.add_decl
(" #include <syslog.h>")
712 self.header
.add_decl
(" #include <libkern/OSByteOrder.h>")
713 self.header
.add_decl
(" #define be32toh(x) OSSwapBigToHostInt32(x)")
714 self.header
.add_decl
("#endif")
715 self.header
.add_decl
("#ifdef _WIN32")
716 self.header
.add_decl
(" #define be32toh(val) _byteswap_ulong(val)")
717 self.header
.add_decl
("#endif")
718 self.header
.add_decl
("#ifdef __pnacl__")
719 self.header
.add_decl
(" #define be16toh(val) (((val) >> 8) | ((val) << 8))")
720 self.header
.add_decl
(" #define be32toh(val) ((be16toh((val) << 16) | (be16toh((val) >> 16))))")
721 self.header
.add_decl
("#endif")
722 self.header
.add_decl
("#ifdef ANDROID")
723 self.header
.add_decl
(" #ifndef be32toh")
724 self.header
.add_decl
(" #define be32toh(val) betoh32(val)")
725 self.header
.add_decl
(" #endif")
726 self.header
.add_decl
(" #include <android/log.h>")
727 self.header
.add_decl
(" #define PRINT_ERROR(...) (void)__android_log_print(ANDROID_LOG_WARN, \"Nit\
", __VA_ARGS__)")
728 self.header
.add_decl
("#elif TARGET_OS_IPHONE")
729 self.header
.add_decl
(" #define PRINT_ERROR(...) syslog(LOG_ERR, __VA_ARGS__)")
730 self.header
.add_decl
("#else")
731 self.header
.add_decl
(" #define PRINT_ERROR(...) fprintf(stderr, __VA_ARGS__)")
732 self.header
.add_decl
("#endif")
734 compile_header_structs
735 compile_nitni_structs
738 var gccd_disable
= modelbuilder
.toolcontext
.opt_no_gcc_directive
.value
739 if gccd_disable
.has
("noreturn") or gccd_disable
.has
("all") then
740 # Signal handler function prototype
741 self.header
.add_decl
("void fatal_exit(int);")
743 self.header
.add_decl
("void fatal_exit(int) __attribute__ ((noreturn));")
746 if gccd_disable
.has
("likely") or gccd_disable
.has
("all") then
747 self.header
.add_decl
("#define likely(x) (x)")
748 self.header
.add_decl
("#define unlikely(x) (x)")
749 else if gccd_disable
.has
("correct-likely") then
750 # invert the `likely` definition
751 # Used by masochists to bench the worst case
752 self.header
.add_decl
("#define likely(x) __builtin_expect((x),0)")
753 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),1)")
755 self.header
.add_decl
("#define likely(x) __builtin_expect((x),1)")
756 self.header
.add_decl
("#define unlikely(x) __builtin_expect((x),0)")
759 # Global variable used by intern methods
760 self.header
.add_decl
("extern int glob_argc;")
761 self.header
.add_decl
("extern char **glob_argv;")
762 self.header
.add_decl
("extern val *glob_sys;")
765 # Stack stocking environment for longjumps
766 protected fun compile_catch_stack
do
767 self.header
.add_decl
"""
768 struct catch_stack_t {
772 extern struct catch_stack_t catchStack;
776 # Declaration of structures for live Nit types
777 protected fun compile_header_structs
is abstract
779 # Declaration of structures for nitni undelying the FFI
780 protected fun compile_nitni_structs
782 self.header
.add_decl
"""
783 /* Native reference to Nit objects */
784 /* This structure is used to represent every Nit type in extern methods and custom C code. */
786 struct nitni_ref *next,
787 *prev; /* adjacent global references in global list */
788 int count; /* number of time this global reference has been marked */
791 /* List of global references from C code to Nit objects */
792 /* Instanciated empty at init of Nit system and filled explicitly by user in C code */
793 struct nitni_global_ref_list_t {
794 struct nitni_ref *head, *tail;
796 extern struct nitni_global_ref_list_t *nitni_global_ref_list;
798 /* Initializer of global reference list */
799 extern void nitni_global_ref_list_init();
801 /* Intern function to add a global reference to the list */
802 extern void nitni_global_ref_add( struct nitni_ref *ref );
804 /* Intern function to remove a global reference from the list */
805 extern void nitni_global_ref_remove( struct nitni_ref *ref );
807 /* Increase count on an existing global reference */
808 extern void nitni_global_ref_incr( struct nitni_ref *ref );
810 /* Decrease count on an existing global reference */
811 extern void nitni_global_ref_decr( struct nitni_ref *ref );
815 fun compile_finalizer_function
817 var finalizable_type
= mainmodule
.finalizable_type
818 if finalizable_type
== null then return
820 var finalize_meth
= mainmodule
.try_get_primitive_method
("finalize", finalizable_type
.mclass
)
822 if finalize_meth
== null then
823 modelbuilder
.toolcontext
.error
(null, "Error: the `Finalizable` class does not declare the `finalize` method.")
827 var v
= self.new_visitor
828 v
.add_decl
"void gc_finalize (void *obj, void *client_data) \{"
829 var recv
= v
.new_expr
("obj", finalizable_type
)
830 v
.send
(finalize_meth
, [recv
])
834 # Hook to add specif piece of code before the the main C function.
836 # Is called by `compile_main_function`
837 fun compile_before_main
(v
: VISITOR)
841 # Hook to add specif piece of code at the begin on the main C function.
843 # Is called by `compile_main_function`
844 fun compile_begin_main
(v
: VISITOR)
848 # Generate the main C function.
852 # * allocate the Sys object if it exists
853 # * call init if is exists
854 # * call main if it exists
855 fun compile_main_function
857 var v
= self.new_visitor
858 v
.add_decl
("#include <signal.h>")
859 var platform
= target_platform
861 var no_main
= platform
.no_main
or modelbuilder
.toolcontext
.opt_no_main
.value
863 if platform
.supports_libunwind
then
864 v
.add_decl
("#ifndef NO_STACKTRACE")
865 v
.add_decl
("#define UNW_LOCAL_ONLY")
866 v
.add_decl
("#include <libunwind.h>")
867 v
.add_decl
("#include \"c_functions_hash
.h\
"")
870 v
.add_decl
("int glob_argc;")
871 v
.add_decl
("char **glob_argv;")
872 v
.add_decl
("val *glob_sys;")
873 v
.add_decl
("struct catch_stack_t catchStack;")
875 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
876 for tag
in count_type_test_tags
do
877 v
.add_decl
("long count_type_test_resolved_{tag};")
878 v
.add_decl
("long count_type_test_unresolved_{tag};")
879 v
.add_decl
("long count_type_test_skipped_{tag};")
880 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
881 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
882 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
886 if self.modelbuilder
.toolcontext
.opt_invocation_metrics
.value
then
887 v
.add_decl
("long count_invoke_by_tables;")
888 v
.add_decl
("long count_invoke_by_direct;")
889 v
.add_decl
("long count_invoke_by_inline;")
890 v
.compiler
.header
.add_decl
("extern long count_invoke_by_tables;")
891 v
.compiler
.header
.add_decl
("extern long count_invoke_by_direct;")
892 v
.compiler
.header
.add_decl
("extern long count_invoke_by_inline;")
895 if self.modelbuilder
.toolcontext
.opt_isset_checks_metrics
.value
then
896 v
.add_decl
("long count_attr_reads = 0;")
897 v
.add_decl
("long count_isset_checks = 0;")
898 v
.compiler
.header
.add_decl
("extern long count_attr_reads;")
899 v
.compiler
.header
.add_decl
("extern long count_isset_checks;")
902 v
.add_decl
("static void show_backtrace(void) \{")
903 if platform
.supports_libunwind
then
904 v
.add_decl
("#ifndef NO_STACKTRACE")
905 v
.add_decl
("char* opt = getenv(\"NIT_NO_STACK\
");")
906 v
.add_decl
("unw_cursor_t cursor;")
907 v
.add_decl
("if(opt==NULL)\{")
908 v
.add_decl
("unw_context_t uc;")
909 v
.add_decl
("unw_word_t ip;")
910 v
.add_decl
("char* procname = malloc(sizeof(char) * 100);")
911 v
.add_decl
("unw_getcontext(&uc);")
912 v
.add_decl
("unw_init_local(&cursor, &uc);")
913 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
914 v
.add_decl
("PRINT_ERROR(\"-- Stack Trace ------------------------------\\n\
");")
915 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
916 v
.add_decl
("while (unw_step(&cursor) > 0) \{")
917 v
.add_decl
(" unw_get_proc_name(&cursor, procname, 100, &ip);")
918 v
.add_decl
(" const char* recv = get_nit_name(procname, strlen(procname));")
919 v
.add_decl
(" if (recv != NULL)\{")
920 v
.add_decl
(" PRINT_ERROR(\"` %s\\n\", recv);")
921 v.add_decl(" \}else\{")
922 v.add_decl(" PRINT_ERROR(\"` %s\\n\
", procname);")
925 v
.add_decl
("PRINT_ERROR(\"-------------------------------------------------\\n\
");")
926 v
.add_decl
("free(procname);")
928 v
.add_decl
("#endif /* NO_STACKTRACE */")
932 v
.add_decl
("void sig_handler(int signo)\{")
933 v
.add_decl
"#ifdef _WIN32"
934 v
.add_decl
"PRINT_ERROR(\"Caught signal
: %s\\n\
", signo);"
936 v
.add_decl
("PRINT_ERROR(\"Caught signal
: %s\\n\
", strsignal(signo));")
938 v
.add_decl
("show_backtrace();")
940 v
.add_decl
("signal(signo, SIG_DFL);")
941 v
.add_decl
"#ifndef _WIN32"
942 v
.add_decl
("kill(getpid(), signo);")
946 v
.add_decl
("void fatal_exit(int status) \{")
947 v
.add_decl
("show_backtrace();")
948 v
.add_decl
("exit(status);")
951 compile_before_main
(v
)
954 v
.add_decl
("int nit_main(int argc, char** argv) \{")
956 v
.add_decl
("int main(int argc, char** argv) \{")
959 compile_begin_main
(v
)
961 v
.add
"#if !defined(__ANDROID__) && !defined(TARGET_OS_IPHONE)"
962 v
.add
("signal(SIGABRT, sig_handler);")
963 v
.add
("signal(SIGFPE, sig_handler);")
964 v
.add
("signal(SIGILL, sig_handler);")
965 v
.add
("signal(SIGINT, sig_handler);")
966 v
.add
("signal(SIGTERM, sig_handler);")
967 v
.add
("signal(SIGSEGV, sig_handler);")
969 v
.add
"#ifndef _WIN32"
970 v
.add
("signal(SIGPIPE, SIG_IGN);")
973 v
.add
("glob_argc = argc; glob_argv = argv;")
974 v
.add
("catchStack.cursor = -1;")
975 v
.add
("initialize_gc_option();")
977 v
.add
"initialize_nitni_global_refs();"
979 var main_type
= mainmodule
.sys_type
980 if main_type
!= null then
981 var mainmodule
= v
.compiler
.mainmodule
982 var glob_sys
= v
.init_instance
(main_type
)
983 v
.add
("glob_sys = {glob_sys};")
984 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
.mclass
)
985 if main_init
!= null then
986 v
.send
(main_init
, [glob_sys
])
988 var main_method
= mainmodule
.try_get_primitive_method
("run", main_type
.mclass
) or else
989 mainmodule
.try_get_primitive_method
("main", main_type
.mclass
)
990 if main_method
!= null then
991 v
.send
(main_method
, [glob_sys
])
995 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
996 v
.add_decl
("long count_type_test_resolved_total = 0;")
997 v
.add_decl
("long count_type_test_unresolved_total = 0;")
998 v
.add_decl
("long count_type_test_skipped_total = 0;")
999 v
.add_decl
("long count_type_test_total_total = 0;")
1000 for tag
in count_type_test_tags
do
1001 v
.add_decl
("long count_type_test_total_{tag};")
1002 v
.add
("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
1003 v
.add
("count_type_test_resolved_total += count_type_test_resolved_{tag};")
1004 v
.add
("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
1005 v
.add
("count_type_test_skipped_total += count_type_test_skipped_{tag};")
1006 v
.add
("count_type_test_total_total += count_type_test_total_{tag};")
1008 v
.add
("printf(\"# dynamic count_type_test: total %l\\n\");")
1009 v
.add
("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\
");")
1010 var tags
= count_type_test_tags
.to_a
1013 v
.add
("printf(\"{tag}\
");")
1014 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
1015 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
1016 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
1017 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\\n\
", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
1021 if self.modelbuilder
.toolcontext
.opt_invocation_metrics
.value
then
1022 v
.add_decl
("long count_invoke_total;")
1023 v
.add
("count_invoke_total = count_invoke_by_tables + count_invoke_by_direct + count_invoke_by_inline;")
1024 v
.add
("printf(\"# dynamic count_invocation: total %ld\\n\", count_invoke_total);")
1025 v
.add
("printf(\"by table
: %ld
(%.2f
%%)\\n\
", count_invoke_by_tables, 100.0*count_invoke_by_tables/count_invoke_total);")
1026 v
.add
("printf(\"direct
: %ld
(%.2f
%%)\\n\
", count_invoke_by_direct, 100.0*count_invoke_by_direct/count_invoke_total);")
1027 v
.add
("printf(\"inlined
: %ld
(%.2f
%%)\\n\
", count_invoke_by_inline, 100.0*count_invoke_by_inline/count_invoke_total);")
1030 if self.modelbuilder
.toolcontext
.opt_isset_checks_metrics
.value
then
1031 v
.add
("printf(\"# dynamic attribute reads: %ld\\n\", count_attr_reads);")
1032 v
.add
("printf(\"# dynamic isset checks: %ld\\n\", count_isset_checks);")
1038 for m
in mainmodule
.in_importation
.greaters
do
1039 var f
= "FILE_"+m
.c_name
1040 v
.add
"const char {f}[] = \"{m.location.file.filename.escape_to_c}\
";"
1041 provide_declaration
(f
, "extern const char {f}[];")
1045 # Copile all C functions related to the [incr|decr]_ref features of the FFI
1046 fun compile_nitni_global_ref_functions
1048 var v
= self.new_visitor
1050 struct nitni_global_ref_list_t *nitni_global_ref_list;
1051 void initialize_nitni_global_refs() {
1052 nitni_global_ref_list = (struct nitni_global_ref_list_t*)nit_alloc(sizeof(struct nitni_global_ref_list_t));
1053 nitni_global_ref_list->head = NULL;
1054 nitni_global_ref_list->tail = NULL;
1057 void nitni_global_ref_add( struct nitni_ref *ref ) {
1058 if ( nitni_global_ref_list->head == NULL ) {
1059 nitni_global_ref_list->head = ref;
1062 nitni_global_ref_list->tail->next = ref;
1063 ref->prev = nitni_global_ref_list->tail;
1065 nitni_global_ref_list->tail = ref;
1070 void nitni_global_ref_remove( struct nitni_ref *ref ) {
1071 if ( ref->prev == NULL ) {
1072 nitni_global_ref_list->head = ref->next;
1074 ref->prev->next = ref->next;
1077 if ( ref->next == NULL ) {
1078 nitni_global_ref_list->tail = ref->prev;
1080 ref->next->prev = ref->prev;
1084 extern void nitni_global_ref_incr( struct nitni_ref *ref ) {
1085 if ( ref->count == 0 ) /* not registered */
1088 nitni_global_ref_add( ref );
1094 extern void nitni_global_ref_decr( struct nitni_ref *ref ) {
1095 if ( ref->count == 1 ) /* was last reference */
1097 /* remove from list */
1098 nitni_global_ref_remove( ref );
1106 # List of additional files required to compile (FFI)
1107 var extern_bodies
= new Array[ExternFile]
1109 # List of source files to copy over to the compile dir
1110 var files_to_copy
= new Array[String]
1112 # This is used to avoid adding an extern file more than once
1113 private var seen_extern
= new ArraySet[String]
1115 # Generate code that initialize the attributes on a new instance
1116 fun generate_init_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
1118 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
1119 self.mainmodule
.linearize_mclassdefs
(cds
)
1121 for npropdef
in modelbuilder
.collect_attr_propdef
(cd
) do
1122 npropdef
.init_expr
(v
, recv
)
1127 # Generate code that check if an attribute is correctly initialized
1128 fun generate_check_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
1130 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
1131 self.mainmodule
.linearize_mclassdefs
(cds
)
1133 for npropdef
in modelbuilder
.collect_attr_propdef
(cd
) do
1134 npropdef
.check_expr
(v
, recv
)
1141 var count_type_test_tags
: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
1142 var count_type_test_resolved
: HashMap[String, Int] = init_count_type_test_tags
1143 var count_type_test_unresolved
: HashMap[String, Int] = init_count_type_test_tags
1144 var count_type_test_skipped
: HashMap[String, Int] = init_count_type_test_tags
1146 protected fun init_count_type_test_tags
: HashMap[String, Int]
1148 var res
= new HashMap[String, Int]
1149 for tag
in count_type_test_tags
do
1155 # Display stats about compilation process
1159 # * type tests against resolved types (`x isa Collection[Animal]`)
1160 # * type tests against unresolved types (`x isa Collection[E]`)
1161 # * type tests skipped
1162 # * type tests total
1165 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1166 print
"# static count_type_test"
1167 print
"\tresolved:\tunresolved\tskipped\ttotal"
1168 var count_type_test_total
= init_count_type_test_tags
1169 count_type_test_resolved
["total"] = 0
1170 count_type_test_unresolved
["total"] = 0
1171 count_type_test_skipped
["total"] = 0
1172 count_type_test_total
["total"] = 0
1173 for tag
in count_type_test_tags
do
1174 count_type_test_total
[tag
] = count_type_test_resolved
[tag
] + count_type_test_unresolved
[tag
] + count_type_test_skipped
[tag
]
1175 count_type_test_resolved
["total"] += count_type_test_resolved
[tag
]
1176 count_type_test_unresolved
["total"] += count_type_test_unresolved
[tag
]
1177 count_type_test_skipped
["total"] += count_type_test_skipped
[tag
]
1178 count_type_test_total
["total"] += count_type_test_total
[tag
]
1180 var count_type_test
= count_type_test_total
["total"]
1181 var tags
= count_type_test_tags
.to_a
1185 printn
"\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
1186 printn
"\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
1187 printn
"\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
1188 printn
"\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
1194 fun finalize_ffi_for_module
(mmodule
: MModule) do mmodule
.finalize_ffi
(self)
1197 # C code file generated from the `writers` and the `required_declarations`
1199 # A file unit aims to be autonomous and is made or one or more `CodeWriter`s.
1201 # Basename of the file, will be appended by `.h` and `.c`
1204 # `CodeWriter` used in sequence to fill the top of the body, then the bottom
1205 var writers
= new Array[CodeWriter]
1207 # Required declarations keys
1209 # See: `provide_declaration`
1210 var required_declarations
= new HashSet[String]
1213 # Store generated lines
1215 # Instances are added to `file.writers` at construction.
1220 # Main lines of code (written at the bottom of the body)
1221 var lines
= new Array[String]
1223 # Lines of code for declarations (written at the top of the body)
1224 var decl_lines
= new Array[String]
1226 # Add a line in the main lines of code (to `lines`)
1227 fun add
(s
: String) do self.lines
.add
(s
)
1229 # Add a declaration line (to `decl_lines`)
1231 # Used for local and global declaration.
1232 fun add_decl
(s
: String) do self.decl_lines
.add
(s
)
1236 file
.writers
.add
(self)
1240 # A visitor on the AST of property definition that generate the C code.
1241 abstract class AbstractCompilerVisitor
1243 type COMPILER: AbstractCompiler
1245 # The associated compiler
1246 var compiler
: COMPILER
1248 # The current visited AST node
1249 var current_node
: nullable ANode = null is writable
1251 # The current `StaticFrame`
1252 var frame
: nullable StaticFrame = null is writable
1254 # Alias for self.compiler.mainmodule.object_type
1255 fun object_type
: MClassType do return self.compiler
.mainmodule
.object_type
1257 # Alias for self.compiler.mainmodule.bool_type
1258 fun bool_type
: MClassType do return self.compiler
.mainmodule
.bool_type
1260 var writer
: CodeWriter is noinit
1264 self.writer
= new CodeWriter(compiler
.files
.last
)
1267 # Force to get the primitive property named `name` in the instance `recv` or abort
1268 fun get_property
(name
: String, recv
: MType): MMethod
1270 assert recv
isa MClassType
1271 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
, name
, recv
.mclass
, self.compiler
.mainmodule
)
1274 fun compile_callsite
(callsite
: CallSite, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1276 if callsite
.is_broken
then return null
1277 var initializers
= callsite
.mpropdef
.initializers
1278 if not initializers
.is_empty
then
1279 var recv
= arguments
.first
1282 for p
in initializers
do
1283 if p
isa MMethod then
1285 for x
in p
.intro
.msignature
.mparameters
do
1286 args
.add arguments
[i
]
1290 else if p
isa MAttribute then
1291 self.write_attribute
(p
, recv
, arguments
[i
])
1295 assert i
== arguments
.length
1297 return self.send
(callsite
.mproperty
, [recv
])
1300 return self.send
(callsite
.mproperty
, arguments
)
1303 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable is abstract
1305 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable]): Bool do return false
1307 # Return an element of a native array.
1308 # The method is unsafe and is just a direct wrapper for the specific implementation of native arrays
1309 fun native_array_get
(native_array
: RuntimeVariable, index
: Int): RuntimeVariable is abstract
1311 # Store an element in a native array.
1312 # The method is unsafe and is just a direct wrapper for the specific implementation of native arrays
1313 fun native_array_set
(native_array
: RuntimeVariable, index
: Int, value
: RuntimeVariable) is abstract
1315 # Allocate `size` bytes with the low_level `nit_alloc` C function
1317 # This method can be redefined to inject statistic or tracing code.
1319 # `tag` if any, is used to mark the class of the allocated object.
1320 fun nit_alloc
(size
: String, tag
: nullable String): String
1322 return "nit_alloc({size})"
1325 # Evaluate `args` as expressions in the call of `mpropdef` on `recv`.
1326 # This method is used to manage varargs in signatures and returns the real array
1327 # of runtime variables to use in the call.
1328 fun varargize
(mpropdef
: MMethodDef, map
: nullable SignatureMap, recv
: RuntimeVariable, args
: SequenceRead[AExpr]): Array[RuntimeVariable]
1330 var msignature
= mpropdef
.new_msignature
or else mpropdef
.msignature
.as(not null)
1331 var res
= new Array[RuntimeVariable]
1334 if msignature
.arity
== 0 then return res
1337 assert args
.length
== msignature
.arity
1339 res
.add
self.expr
(ne
, null)
1344 # Eval in order of arguments, not parameters
1345 var exprs
= new Array[RuntimeVariable].with_capacity
(args
.length
)
1347 exprs
.add
self.expr
(ne
, null)
1350 # Fill `res` with the result of the evaluation according to the mapping
1351 for i
in [0..msignature
.arity
[ do
1352 var param
= msignature
.mparameters
[i
]
1353 var j
= map
.map
.get_or_null
(i
)
1356 res
.add
(null_instance
)
1359 if param
.is_vararg
and args
[i
].vararg_decl
> 0 then
1360 var vararg
= exprs
.sub
(j
, args
[i
].vararg_decl
)
1361 var elttype
= param
.mtype
1362 var arg
= self.vararg_instance
(mpropdef
, recv
, vararg
, elttype
)
1373 # Anchor a type to the main module and the current receiver
1374 fun anchor
(mtype
: MType): MType
1376 if not mtype
.need_anchor
then return mtype
1377 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
1380 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
1382 if not mtype
.need_anchor
then return mtype
1383 return mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
1386 # Unsafely cast a value to a new type
1387 # ie the result share the same C variable but my have a different mcasttype
1388 # NOTE: if the adaptation is useless then `value` is returned as it.
1389 # ENSURE: `result.name == value.name`
1390 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1392 mtype
= self.anchor
(mtype
)
1393 var valmtype
= value
.mcasttype
1395 # Do nothing if useless autocast
1396 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1400 # Just as_not_null if the target is not nullable.
1402 # eg `nullable PreciseType` adapted to `Object` gives precisetype.
1403 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1404 mtype
= valmtype
.mtype
1407 var res
= new RuntimeVariable(value
.name
, value
.mtype
, mtype
)
1411 # Generate a super call from a method definition
1412 fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1414 # Adapt the arguments of a method according to targetted `MMethodDef`
1415 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable]) is abstract
1417 # Unbox all the arguments of a method when implemented `extern` or `intern`
1418 fun unbox_signature_extern
(m
: MMethodDef, args
: Array[RuntimeVariable]) is abstract
1420 # Box or unbox a value to another type iff a C type conversion is needed
1421 # ENSURE: `result.mtype.ctype == mtype.ctype`
1422 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
1424 # Box extern classes to be used in the generated code
1425 fun box_extern
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
1427 # Unbox extern classes to be used in extern code (legacy NI and FFI)
1428 fun unbox_extern
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
1430 # Generate a polymorphic subtype test
1431 fun type_test
(value
: RuntimeVariable, mtype
: MType, tag
: String): RuntimeVariable is abstract
1433 # Generate the code required to dynamically check if 2 objects share the same runtime type
1434 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
1436 # Generate a Nit "is" for two runtime_variables
1437 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
1441 # Generate a static call on a method definition
1442 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1444 # Generate a polymorphic send for the method `m` and the arguments `args`
1445 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1447 # Generate a monomorphic send for the method `m`, the type `t` and the arguments `args`
1448 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1450 assert t
isa MClassType
1451 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
1452 return self.call
(propdef
, t
, args
)
1455 # Generate a monomorphic super send from the method `m`, the type `t` and the arguments `args`
1456 fun monomorphic_super_send
(m
: MMethodDef, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1458 assert t
isa MClassType
1459 m
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
1460 return self.call
(m
, t
, args
)
1463 # Attributes handling
1465 # Generate a polymorphic attribute is_set test
1466 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
1468 # Generate a polymorphic attribute read
1469 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
1471 # Generate a polymorphic attribute write
1472 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable) is abstract
1476 # Can value be null? (according to current knowledge)
1477 fun maybe_null
(value
: RuntimeVariable): Bool
1479 return value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType
1482 # Add a check and an abort for a null receiver if needed
1483 fun check_recv_notnull
(recv
: RuntimeVariable)
1485 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
then return
1487 if maybe_null
(recv
) then
1488 self.add
("if (unlikely({recv} == NULL)) \{")
1489 self.add_abort
("Receiver is null")
1496 private var names
= new HashSet[String]
1497 private var last
: Int = 0
1499 # Return a new name based on `s` and unique in the visitor
1500 fun get_name
(s
: String): String
1502 if not self.names
.has
(s
) then
1506 var i
= self.last
+ 1
1509 if not self.names
.has
(s2
) then
1518 # Return an unique and stable identifier associated with an escapemark
1519 fun escapemark_name
(e
: nullable EscapeMark): String
1522 if frame
.escapemark_names
.has_key
(e
) then return frame
.escapemark_names
[e
]
1524 if name
== null then name
= "label"
1525 name
= get_name
(name
)
1526 frame
.escapemark_names
[e
] = name
1530 # Insert a C label for associated with an escapemark
1531 fun add_escape_label
(e
: nullable EscapeMark)
1533 if e
== null then return
1534 if e
.escapes
.is_empty
then return
1535 add
("BREAK_{escapemark_name(e)}: (void)0;")
1538 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1539 # NOTE: we do not return a `RuntimeVariable` "CString" as the class may not exist in the module/program
1540 fun class_name_string
(value
: RuntimeVariable): String is abstract
1542 # Variables handling
1544 protected var variables
= new HashMap[Variable, RuntimeVariable]
1546 # Return the local runtime_variable associated to a Nit local variable
1547 fun variable
(variable
: Variable): RuntimeVariable
1549 if self.variables
.has_key
(variable
) then
1550 return self.variables
[variable
]
1552 var name
= self.get_name
("var_{variable.name}")
1553 var mtype
= variable
.declared_type
.as(not null)
1554 mtype
= self.anchor
(mtype
)
1555 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1556 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1557 self.variables
[variable
] = res
1562 # Return a new uninitialized local runtime_variable
1563 fun new_var
(mtype
: MType): RuntimeVariable
1565 mtype
= self.anchor
(mtype
)
1566 var name
= self.get_name
("var")
1567 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1568 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1572 # The difference with `new_var` is the C static type of the local variable
1573 fun new_var_extern
(mtype
: MType): RuntimeVariable
1575 mtype
= self.anchor
(mtype
)
1576 var name
= self.get_name
("var")
1577 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1578 self.add_decl
("{mtype.ctype_extern} {name} /* : {mtype} for extern */;")
1582 # Return a new uninitialized named runtime_variable
1583 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
1585 mtype
= self.anchor
(mtype
)
1586 var res
= new RuntimeVariable(name
, mtype
, mtype
)
1587 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
1591 # Correctly assign a left and a right value
1592 # Boxing and unboxing is performed if required
1593 fun assign
(left
, right
: RuntimeVariable)
1595 right
= self.autobox
(right
, left
.mtype
)
1596 self.add
("{left} = {right};")
1599 # Generate instances
1601 # Generate a alloc-instance + init-attributes
1602 fun init_instance
(mtype
: MClassType): RuntimeVariable is abstract
1604 # Allocate and init attributes of an instance of a standard or extern class
1606 # Does not support universals and the pseudo-internal `NativeArray` class.
1607 fun init_instance_or_extern
(mtype
: MClassType): RuntimeVariable
1610 var ctype
= mtype
.ctype
1611 assert mtype
.mclass
.name
!= "NativeArray"
1612 if not mtype
.is_c_primitive
then
1613 recv
= init_instance
(mtype
)
1614 else if ctype
== "char*" then
1615 recv
= new_expr
("NULL/*special!*/", mtype
)
1617 recv
= new_expr
("({ctype})0/*special!*/", mtype
)
1622 # Set a GC finalizer on `recv`, only if `recv` isa Finalizable
1623 fun set_finalizer
(recv
: RuntimeVariable)
1625 var mtype
= recv
.mtype
1626 var finalizable_type
= compiler
.mainmodule
.finalizable_type
1627 if finalizable_type
!= null and not mtype
.need_anchor
and
1628 mtype
.is_subtype
(compiler
.mainmodule
, null, finalizable_type
) then
1629 add
"gc_register_finalizer({recv});"
1633 # The currently processed module
1635 # alias for `compiler.mainmodule`
1636 fun mmodule
: MModule do return compiler
.mainmodule
1638 # Generate an integer value
1639 fun int_instance
(value
: Int): RuntimeVariable
1641 var t
= mmodule
.int_type
1642 var res
= new RuntimeVariable("{value.to_s}l", t
, t
)
1646 # Generate a byte value
1647 fun byte_instance
(value
: Byte): RuntimeVariable
1649 var t
= mmodule
.byte_type
1650 var res
= new RuntimeVariable("((unsigned char){value.to_s})", t
, t
)
1654 # Generate an int8 value
1655 fun int8_instance
(value
: Int8): RuntimeVariable
1657 var t
= mmodule
.int8_type
1658 var res
= new RuntimeVariable("INT8_C({value.to_s})", t
, t
)
1662 # Generate an int16 value
1663 fun int16_instance
(value
: Int16): RuntimeVariable
1665 var t
= mmodule
.int16_type
1666 var res
= new RuntimeVariable("INT16_C({value.to_s})", t
, t
)
1670 # Generate a uint16 value
1671 fun uint16_instance
(value
: UInt16): RuntimeVariable
1673 var t
= mmodule
.uint16_type
1674 var res
= new RuntimeVariable("UINT16_C({value.to_s})", t
, t
)
1678 # Generate an int32 value
1679 fun int32_instance
(value
: Int32): RuntimeVariable
1681 var t
= mmodule
.int32_type
1682 var res
= new RuntimeVariable("INT32_C({value.to_s})", t
, t
)
1686 # Generate a uint32 value
1687 fun uint32_instance
(value
: UInt32): RuntimeVariable
1689 var t
= mmodule
.uint32_type
1690 var res
= new RuntimeVariable("UINT32_C({value.to_s})", t
, t
)
1694 # Generate a char value
1695 fun char_instance
(value
: Char): RuntimeVariable
1697 var t
= mmodule
.char_type
1699 if value
.code_point
< 128 then
1700 return new RuntimeVariable("'{value.to_s.escape_to_c}'", t
, t
)
1702 return new RuntimeVariable("{value.code_point}", t
, t
)
1706 # Generate a float value
1708 # FIXME pass a Float, not a string
1709 fun float_instance
(value
: String): RuntimeVariable
1711 var t
= mmodule
.float_type
1712 var res
= new RuntimeVariable("{value}", t
, t
)
1716 # Generate an integer value
1717 fun bool_instance
(value
: Bool): RuntimeVariable
1719 var s
= if value
then "1" else "0"
1720 var res
= new RuntimeVariable(s
, bool_type
, bool_type
)
1724 # Generate the `null` value
1725 fun null_instance
: RuntimeVariable
1727 var t
= compiler
.mainmodule
.model
.null_type
1728 var res
= new RuntimeVariable("((val*)NULL)", t
, t
)
1732 # Generates a CString instance fully escaped in C-style \xHH fashion
1733 fun c_string_instance
(ns
: CString, len
: Int): RuntimeVariable do
1734 var mtype
= mmodule
.c_string_type
1735 var nat
= new_var
(mtype
)
1736 var byte_esc
= new Buffer.with_cap
(len
* 4)
1737 for i
in [0 .. len
[ do
1738 byte_esc
.append
("\\x{ns[i].to_s.substring_from(2)}")
1740 self.add
("{nat} = \"{byte_esc}\
";")
1744 # Generate a string value
1745 fun string_instance
(string
: String): RuntimeVariable
1747 var mtype
= mmodule
.string_type
1748 var name
= self.get_name
("varonce")
1749 self.add_decl
("static {mtype.ctype} {name};")
1750 var res
= self.new_var
(mtype
)
1751 self.add
("if (likely({name}!=NULL)) \{")
1752 self.add
("{res} = {name};")
1753 self.add
("\} else \{")
1754 var native_mtype
= mmodule
.c_string_type
1755 var nat
= self.new_var
(native_mtype
)
1756 self.add
("{nat} = \"{string.escape_to_c}\
";")
1757 var byte_length
= self.int_instance
(string
.byte_length
)
1758 var unilen
= self.int_instance
(string
.length
)
1759 self.add
("{res} = {self.send(self.get_property("to_s_unsafe", native_mtype), [nat, byte_length, unilen, value_instance(false), value_instance(false)]).as(not null)};")
1760 self.add
("{name} = {res};")
1765 fun value_instance
(object
: Object): RuntimeVariable
1767 if object
isa Int then
1768 return int_instance
(object
)
1769 else if object
isa Bool then
1770 return bool_instance
(object
)
1771 else if object
isa String then
1772 return string_instance
(object
)
1778 # Generate an array value
1779 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
1781 # Get an instance of a array for a vararg
1782 fun vararg_instance
(mpropdef
: MPropDef, recv
: RuntimeVariable, varargs
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
1786 # Add a line in the main part of the generated C
1787 fun add
(s
: String) do self.writer
.lines
.add
(s
)
1790 # (used for local or global declaration)
1791 fun add_decl
(s
: String) do self.writer
.decl_lines
.add
(s
)
1793 # Request the presence of a global declaration
1794 fun require_declaration
(key
: String)
1796 var reqs
= self.writer
.file
.required_declarations
1797 if reqs
.has
(key
) then return
1799 var node
= current_node
1800 if node
!= null then compiler
.requirers_of_declarations
[key
] = node
1803 # Add a declaration in the local-header
1804 # The declaration is ensured to be present once
1805 fun declare_once
(s
: String)
1807 self.compiler
.provide_declaration
(s
, s
)
1808 self.require_declaration
(s
)
1811 # Look for a needed .h and .c file for a given module
1812 # This is used for the legacy FFI
1813 fun add_extern
(mmodule
: MModule)
1815 var file
= mmodule
.filepath
1816 file
= file
.strip_extension
(".nit")
1817 var tryfile
= file
+ ".nit.h"
1818 if tryfile
.file_exists
then
1819 self.declare_once
("#include \"{tryfile.basename}\
"")
1820 self.compiler
.files_to_copy
.add
(tryfile
)
1822 tryfile
= file
+ "_nit.h"
1823 if tryfile
.file_exists
then
1824 self.declare_once
("#include \"{tryfile.basename}\
"")
1825 self.compiler
.files_to_copy
.add
(tryfile
)
1828 if self.compiler
.seen_extern
.has
(file
) then return
1829 self.compiler
.seen_extern
.add
(file
)
1830 tryfile
= file
+ ".nit.c"
1831 if not tryfile
.file_exists
then
1832 tryfile
= file
+ "_nit.c"
1833 if not tryfile
.file_exists
then return
1835 var f
= new ExternCFile(tryfile
.basename
, "")
1836 self.compiler
.extern_bodies
.add
(f
)
1837 self.compiler
.files_to_copy
.add
(tryfile
)
1840 # Return a new local runtime_variable initialized with the C expression `cexpr`.
1841 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
1843 var res
= new_var
(mtype
)
1844 self.add
("{res} = {cexpr};")
1848 # Generate generic abort
1849 # used by aborts, asserts, casts, etc.
1850 fun add_abort
(message
: String)
1853 self.add
("PRINT_ERROR(\"Runtime error
: %s\
", \"{message.escape_to_c}\
");")
1857 # Generate a long jump if there is a catch block.
1859 # This method should be called before the error messages and before a `add_raw_abort`.
1862 self.add
("if(catchStack.cursor >= 0)\{")
1863 self.add
("longjmp(catchStack.envs[catchStack.cursor], 1);")
1867 # Generate abort without a message.
1869 # Used when one need a more complex message.
1870 # Do not forget to call `add_raw_abort` before the display of a custom user message.
1873 var current_node
= self.current_node
1874 if current_node
!= null and current_node
.location
.file
!= null and
1875 current_node
.location
.file
.mmodule
!= null then
1876 var f
= "FILE_{self.current_node.location.file.mmodule.c_name}"
1877 self.require_declaration
(f
)
1878 self.add
("PRINT_ERROR(\" (%s
:%d
)\\n\
", {f}, {current_node.location.line_start});")
1880 self.add
("PRINT_ERROR(\"\\n\
");")
1882 self.add
("fatal_exit(1);")
1885 # Add a dynamic cast
1886 fun add_cast
(value
: RuntimeVariable, mtype
: MType, tag
: String)
1888 var res
= self.type_test
(value
, mtype
, tag
)
1889 self.add
("if (unlikely(!{res})) \{")
1891 var cn
= self.class_name_string
(value
)
1892 self.add
("PRINT_ERROR(\"Runtime error
: Cast failed
. Expected `%s`, got
`%s`\
", \"{mtype.to_s.escape_to_c}\
", {cn});")
1897 # Generate a return with the value `s`
1898 fun ret
(s
: RuntimeVariable)
1900 self.assign
(self.frame
.returnvar
.as(not null), s
)
1901 self.add
("goto {self.frame.returnlabel.as(not null)};")
1904 # Compile a statement (if any)
1905 fun stmt
(nexpr
: nullable AExpr)
1907 if nexpr
== null then return
1908 if nexpr
.is_broken
then
1909 # Untyped expression.
1910 # Might mean dead code or invalid code
1912 add_abort
("FATAL: bad statement executed.")
1916 var narray
= nexpr
.comprehension
1917 if narray
!= null then
1918 var recv
= frame
.comprehension
.as(not null)
1919 var val
= expr
(nexpr
, narray
.element_mtype
)
1920 compile_callsite
(narray
.push_callsite
.as(not null), [recv
, val
])
1924 var old
= self.current_node
1925 self.current_node
= nexpr
1927 self.current_node
= old
1930 # Compile an expression an return its result
1931 # `mtype` is the expected return type, pass null if no specific type is expected.
1932 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
1934 var old
= self.current_node
1935 self.current_node
= nexpr
1938 if nexpr
.mtype
!= null then
1939 res
= nexpr
.expr
(self)
1943 # Untyped expression.
1944 # Might mean dead code or invalid code.
1946 add_abort
("FATAL: bad expression executed.")
1947 # and return a placebo result to please the C compiler
1948 if mtype
== null then mtype
= compiler
.mainmodule
.object_type
1949 res
= new_var
(mtype
)
1951 self.current_node
= old
1955 if mtype
!= null then
1956 mtype
= self.anchor
(mtype
)
1957 res
= self.autobox
(res
, mtype
)
1959 res
= autoadapt
(res
, nexpr
.mtype
.as(not null))
1960 var implicit_cast_to
= nexpr
.implicit_cast_to
1961 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
1962 add_cast
(res
, implicit_cast_to
, "auto")
1963 res
= autoadapt
(res
, implicit_cast_to
)
1965 self.current_node
= old
1969 # Alias for `self.expr(nexpr, self.bool_type)`
1970 fun expr_bool
(nexpr
: AExpr): RuntimeVariable do return expr
(nexpr
, bool_type
)
1972 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1973 fun debug
(message
: String)
1975 var node
= self.current_node
1976 if node
== null then
1977 print
"?: {message}"
1981 self.add
("/* DEBUG: {message} */")
1985 # A C function associated to a Nit method
1986 # Because of customization, a given Nit method can be compiler more that once
1987 abstract class AbstractRuntimeFunction
1989 type COMPILER: AbstractCompiler
1990 type VISITOR: AbstractCompilerVisitor
1992 # The associated Nit method
1993 var mmethoddef
: MMethodDef
1995 # The mangled c name of the runtime_function
1996 # Subclasses should redefine `build_c_name` instead
1999 var res
= self.c_name_cache
2000 if res
!= null then return res
2001 res
= self.build_c_name
2002 self.c_name_cache
= res
2006 # Non cached version of `c_name`
2007 protected fun build_c_name
: String is abstract
2009 protected var c_name_cache
: nullable String = null is writable
2011 # Implements a call of the runtime_function
2012 # May inline the body or generate a C function call
2013 fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
2015 # Generate the code for the `AbstractRuntimeFunction`
2016 # Warning: compile more than once compilation makes CC unhappy
2017 fun compile_to_c
(compiler
: COMPILER) is abstract
2020 # A runtime variable hold a runtime value in C.
2021 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
2023 # 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.
2024 class RuntimeVariable
2025 # The name of the variable in the C code
2028 # The static type of the variable (as declard in C)
2031 # The current casted type of the variable (as known in Nit)
2032 var mcasttype
: MType is writable
2034 # If the variable exaclty a mcasttype?
2035 # false (usual value) means that the variable is a mcasttype or a subtype.
2036 var is_exact
: Bool = false is writable
2040 assert not mtype
.need_anchor
2041 assert not mcasttype
.need_anchor
2044 redef fun to_s
do return name
2049 if self.is_exact
then
2050 exact_str
= " exact"
2055 if self.mtype
== self.mcasttype
then
2056 type_str
= "{mtype}{exact_str}"
2058 type_str
= "{mtype}({mcasttype}{exact_str})"
2060 return "<{name}:{type_str}>"
2064 # The static context of a visited property in a `AbstractCompilerVisitor`
2067 type VISITOR: AbstractCompilerVisitor
2069 # The associated visitor
2070 var visitor
: VISITOR
2072 # The executed property.
2073 # A Method in case of a call, an attribute in case of a default initialization.
2074 var mpropdef
: MPropDef
2076 # The static type of the receiver
2077 var receiver
: MClassType
2079 # Arguments of the method (the first is the receiver)
2080 var arguments
: Array[RuntimeVariable]
2082 # The runtime_variable associated to the return (in a function)
2083 var returnvar
: nullable RuntimeVariable = null is writable
2085 # The label at the end of the property
2086 var returnlabel
: nullable String = null is writable
2088 # Labels associated to a each escapemarks.
2089 # Because of inlinings, escape-marks must be associated to their context (the frame)
2090 private var escapemark_names
= new HashMap[EscapeMark, String]
2092 # The array comprehension currently filled, if any
2093 private var comprehension
: nullable RuntimeVariable = null
2097 # Return the C type associated to a given Nit static type
2098 fun ctype
: String do return "val*"
2100 # C type outside of the compiler code and in boxes
2101 fun ctype_extern
: String do return "val*"
2103 # Short name of the `ctype` to use in unions
2104 fun ctypename
: String do return "val"
2106 # Is the associated C type a primitive one?
2108 # ENSURE `result == (ctype != "val*")`
2109 fun is_c_primitive
: Bool do return false
2112 redef class MClassType
2114 redef var ctype
is lazy
do
2115 if mclass
.name
== "Int" then
2117 else if mclass
.name
== "Bool" then
2119 else if mclass
.name
== "Char" then
2121 else if mclass
.name
== "Float" then
2123 else if mclass
.name
== "Int8" then
2125 else if mclass
.name
== "Byte" then
2126 return "unsigned char"
2127 else if mclass
.name
== "Int16" then
2129 else if mclass
.name
== "UInt16" then
2131 else if mclass
.name
== "Int32" then
2133 else if mclass
.name
== "UInt32" then
2135 else if mclass
.name
== "CString" then
2137 else if mclass
.name
== "NativeArray" then
2144 redef var is_c_primitive
is lazy
do return ctype
!= "val*"
2146 redef fun ctype_extern
: String
2148 if mclass
.kind
== extern_kind
then
2155 redef fun ctypename
: String
2157 if mclass
.name
== "Int" then
2159 else if mclass
.name
== "Bool" then
2161 else if mclass
.name
== "Char" then
2163 else if mclass
.name
== "Float" then
2165 else if mclass
.name
== "Int8" then
2167 else if mclass
.name
== "Byte" then
2169 else if mclass
.name
== "Int16" then
2171 else if mclass
.name
== "UInt16" then
2173 else if mclass
.name
== "Int32" then
2175 else if mclass
.name
== "UInt32" then
2177 else if mclass
.name
== "CString" then
2179 else if mclass
.name
== "NativeArray" then
2180 #return "{self.arguments.first.ctype}*"
2188 redef class MPropDef
2189 type VISITOR: AbstractCompilerVisitor
2192 redef class MMethodDef
2193 # Can the body be inlined?
2194 fun can_inline
(v
: VISITOR): Bool
2196 if is_abstract
then return true
2197 if constant_value
!= null then return true
2198 var modelbuilder
= v
.compiler
.modelbuilder
2199 var node
= modelbuilder
.mpropdef2node
(self)
2200 if node
isa APropdef then
2201 return node
.can_inline
2202 else if node
isa AClassdef then
2203 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
2205 else if node
== null then
2212 # Inline the body in another visitor
2213 fun compile_inside_to_c
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
2215 var modelbuilder
= v
.compiler
.modelbuilder
2216 var val
= constant_value
2217 var node
= modelbuilder
.mpropdef2node
(self)
2221 var cn
= v
.class_name_string
(arguments
.first
)
2222 v
.current_node
= node
2223 v
.add
("PRINT_ERROR(\"Runtime error
: Abstract method
`%s` called on
`%s`\
", \"{mproperty.name.escape_to_c}\
", {cn});")
2228 if node
isa APropdef then
2229 var oldnode
= v
.current_node
2230 v
.current_node
= node
2231 self.compile_parameter_check
(v
, arguments
)
2232 node
.compile_to_c
(v
, self, arguments
)
2233 v
.current_node
= oldnode
2234 else if node
isa AClassdef then
2235 var oldnode
= v
.current_node
2236 v
.current_node
= node
2237 self.compile_parameter_check
(v
, arguments
)
2238 node
.compile_to_c
(v
, self, arguments
)
2239 v
.current_node
= oldnode
2240 else if val
!= null then
2241 v
.ret
(v
.value_instance
(val
))
2248 # Generate type checks in the C code to check covariant parameters
2249 fun compile_parameter_check
(v
: VISITOR, arguments
: Array[RuntimeVariable])
2251 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_covariance
.value
then return
2253 var msignature
= self.msignature
.as(not null)
2255 for i
in [0..msignature
.arity
[ do
2256 var mp
= msignature
.mparameters
[i
]
2257 # skip test for vararg since the array is instantiated with the correct polymorphic type
2258 if mp
.is_vararg
then continue
2260 # skip if the cast is not required
2261 var origmtype
= self.mproperty
.intro
.msignature
.mparameters
[i
].mtype
2262 if not origmtype
.need_anchor
then continue
2264 # get the parameter type
2265 var mtype
= mp
.mtype
2268 # note that v decides if and how to implements the cast
2269 v
.add
("/* Covariant cast for argument {i} ({mp.name}) {arguments[i+1].inspect} isa {mtype} */")
2270 v
.add_cast
(arguments
[i
+1], mtype
, "covariance")
2277 redef class APropdef
2278 fun compile_to_c
(v
: AbstractCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
2280 v
.add
("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
2281 debug
("Not yet implemented")
2284 fun can_inline
: Bool do return true
2287 redef class AMethPropdef
2288 redef fun compile_to_c
(v
, mpropdef
, arguments
)
2290 # Call the implicit super-init
2291 var auto_super_inits
= self.auto_super_inits
2292 if auto_super_inits
!= null then
2293 var args
= [arguments
.first
]
2294 for auto_super_init
in auto_super_inits
do
2295 assert auto_super_init
.mproperty
!= mpropdef
.mproperty
2297 for i
in [0..auto_super_init
.msignature
.arity
+1[ do
2298 args
.add
(arguments
[i
])
2300 assert auto_super_init
.mproperty
!= mpropdef
.mproperty
2301 v
.compile_callsite
(auto_super_init
, args
)
2304 if auto_super_call
then
2305 v
.supercall
(mpropdef
, arguments
.first
.mtype
.as(MClassType), arguments
)
2308 # Try special compilation
2309 if mpropdef
.is_intern
then
2310 if compile_intern_to_c
(v
, mpropdef
, arguments
) then return
2312 if mpropdef
.is_extern
then
2313 if mpropdef
.mproperty
.is_init
then
2314 if compile_externinit_to_c
(v
, mpropdef
, arguments
) then return
2316 if compile_externmeth_to_c
(v
, mpropdef
, arguments
) then return
2320 # Compile block if any
2321 var n_block
= n_block
2322 if n_block
!= null then
2323 for i
in [0..mpropdef
.msignature
.arity
[ do
2324 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
2325 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
2333 var cn
= v
.class_name_string
(arguments
.first
)
2334 v
.add
("PRINT_ERROR(\"Runtime error
: uncompiled method
`%s` called on
`%s`. NOT YET IMPLEMENTED\
", \"{mpropdef.mproperty.name.escape_to_c}\
", {cn});")
2338 redef fun can_inline
2340 if self.auto_super_inits
!= null then return false
2341 var nblock
= self.n_block
2342 if nblock
== null then return true
2343 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
2344 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
2348 fun compile_intern_to_c
(v
: AbstractCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable]): Bool
2350 var pname
= mpropdef
.mproperty
.name
2351 var cname
= mpropdef
.mclassdef
.mclass
.name
2352 var ret
= mpropdef
.msignature
.return_mtype
2354 ret
= v
.resolve_for
(ret
, arguments
.first
)
2356 if pname
!= "==" and pname
!= "!=" then
2357 v
.adapt_signature
(mpropdef
, arguments
)
2358 v
.unbox_signature_extern
(mpropdef
, arguments
)
2360 if cname
== "Int" then
2361 if pname
== "output" then
2362 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
2364 else if pname
== "object_id" then
2365 v
.ret
(arguments
.first
)
2367 else if pname
== "+" then
2368 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2370 else if pname
== "-" then
2371 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2373 else if pname
== "unary -" then
2374 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2376 else if pname
== "unary +" then
2379 else if pname
== "*" then
2380 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2382 else if pname
== "/" then
2383 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2385 else if pname
== "%" then
2386 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2388 else if pname
== "==" then
2389 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2391 else if pname
== "!=" then
2392 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2393 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2395 else if pname
== "<" then
2396 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2398 else if pname
== ">" then
2399 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2401 else if pname
== "<=" then
2402 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2404 else if pname
== ">=" then
2405 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2407 else if pname
== "to_i8" then
2408 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
2410 else if pname
== "to_i16" then
2411 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
2413 else if pname
== "to_u16" then
2414 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
2416 else if pname
== "to_i32" then
2417 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2419 else if pname
== "to_u32" then
2420 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2422 else if pname
== "to_f" then
2423 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
2425 else if pname
== "to_b" then
2426 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2428 else if pname
== "code_point" then
2429 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2431 else if pname
== "&" then
2432 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
2434 else if pname
== "|" then
2435 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
2437 else if pname
== ">>" then
2438 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2440 else if pname
== "<<" then
2441 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2444 else if cname
== "Char" then
2445 if pname
== "object_id" then
2446 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2448 else if pname
== "successor" then
2449 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2451 else if pname
== "predecessor" then
2452 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2454 else if pname
== "==" then
2455 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2457 else if pname
== "!=" then
2458 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2459 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2461 else if pname
== "<" then
2462 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2464 else if pname
== ">" then
2465 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2467 else if pname
== "<=" then
2468 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2470 else if pname
== ">=" then
2471 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2473 else if pname
== "to_i" then
2474 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
2476 else if pname
== "code_point" then
2477 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2480 else if cname
== "Byte" then
2481 if pname
== "output" then
2482 v
.add
("printf(\"%x\\n\
", {arguments.first});")
2484 else if pname
== "object_id" then
2485 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2487 else if pname
== "+" then
2488 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2490 else if pname
== "-" then
2491 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2493 else if pname
== "unary -" then
2494 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2496 else if pname
== "unary +" then
2499 else if pname
== "*" then
2500 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2502 else if pname
== "/" then
2503 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2505 else if pname
== "%" then
2506 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2508 else if pname
== "==" then
2509 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2511 else if pname
== "!=" then
2512 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2513 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2515 else if pname
== "<" then
2516 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2518 else if pname
== ">" then
2519 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2521 else if pname
== "<=" then
2522 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2524 else if pname
== ">=" then
2525 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2527 else if pname
== ">>" then
2528 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2530 else if pname
== "<<" then
2531 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2533 else if pname
== "&" then
2534 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
2536 else if pname
== "to_i" then
2537 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2539 else if pname
== "to_f" then
2540 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
2542 else if pname
== "to_i8" then
2543 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
2545 else if pname
== "to_i16" then
2546 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
2548 else if pname
== "to_u16" then
2549 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
2551 else if pname
== "to_i32" then
2552 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2554 else if pname
== "to_u32" then
2555 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2557 else if pname
== "ascii" then
2558 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2561 else if cname
== "Bool" then
2562 if pname
== "output" then
2563 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
2565 else if pname
== "object_id" then
2566 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2568 else if pname
== "==" then
2569 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2571 else if pname
== "!=" then
2572 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2573 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2576 else if cname
== "Float" then
2577 if pname
== "output" then
2578 v
.add
("printf(\"%f\\n\
", {arguments.first});")
2580 else if pname
== "object_id" then
2581 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
2583 else if pname
== "+" then
2584 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2586 else if pname
== "-" then
2587 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2589 else if pname
== "unary -" then
2590 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2592 else if pname
== "unary +" then
2595 else if pname
== "succ" then
2596 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
2598 else if pname
== "prec" then
2599 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
2601 else if pname
== "*" then
2602 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2604 else if pname
== "/" then
2605 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2607 else if pname
== "==" then
2608 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2610 else if pname
== "!=" then
2611 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2612 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2614 else if pname
== "<" then
2615 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2617 else if pname
== ">" then
2618 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2620 else if pname
== "<=" then
2621 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2623 else if pname
== ">=" then
2624 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2626 else if pname
== "to_i" then
2627 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2629 else if pname
== "to_b" then
2630 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2632 else if pname
== "to_i8" then
2633 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
2635 else if pname
== "to_i16" then
2636 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
2638 else if pname
== "to_u16" then
2639 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
2641 else if pname
== "to_i32" then
2642 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2644 else if pname
== "to_u32" then
2645 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2648 else if cname
== "CString" then
2649 if pname
== "[]" then
2650 v
.ret
(v
.new_expr
("(unsigned char)((int){arguments[0]}[{arguments[1]}])", ret
.as(not null)))
2652 else if pname
== "[]=" then
2653 v
.add
("{arguments[0]}[{arguments[1]}]=(unsigned char){arguments[2]};")
2655 else if pname
== "copy_to" then
2656 v
.add
("memmove({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2658 else if pname
== "atoi" then
2659 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
2661 else if pname
== "fast_cstring" then
2662 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2664 else if pname
== "==" then
2665 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2667 else if pname
== "!=" then
2668 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2669 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2671 else if pname
== "new" then
2672 var alloc
= v
.nit_alloc
(arguments
[1].to_s
, "CString")
2673 v
.ret
(v
.new_expr
("(char*){alloc}", ret
.as(not null)))
2675 else if pname
== "fetch_4_chars" then
2676 v
.ret
(v
.new_expr
("*((uint32_t*)({arguments[0]} + {arguments[1]}))", ret
.as(not null)))
2678 else if pname
== "fetch_4_hchars" then
2679 v
.ret
(v
.new_expr
("(uint32_t)be32toh(*((uint32_t*)({arguments[0]} + {arguments[1]})))", ret
.as(not null)))
2682 else if cname
== "NativeArray" then
2683 return v
.native_array_def
(pname
, ret
, arguments
)
2684 else if cname
== "Int8" then
2685 if pname
== "output" then
2686 v
.add
("printf(\"%\
"PRIi8 \"\\n\
", {arguments.first});")
2688 else if pname
== "object_id" then
2689 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2691 else if pname
== "+" then
2692 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2694 else if pname
== "-" then
2695 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2697 else if pname
== "unary -" then
2698 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2700 else if pname
== "unary +" then
2703 else if pname
== "*" then
2704 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2706 else if pname
== "/" then
2707 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2709 else if pname
== "%" then
2710 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2712 else if pname
== "<<" then
2713 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2715 else if pname
== ">>" then
2716 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2718 else if pname
== "==" then
2719 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2721 else if pname
== "!=" then
2722 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2723 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2725 else if pname
== "<" then
2726 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2728 else if pname
== ">" then
2729 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2731 else if pname
== "<=" then
2732 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2734 else if pname
== ">=" then
2735 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2737 else if pname
== "to_i" then
2738 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2740 else if pname
== "to_b" then
2741 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2743 else if pname
== "to_i16" then
2744 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
2746 else if pname
== "to_u16" then
2747 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
2749 else if pname
== "to_i32" then
2750 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2752 else if pname
== "to_u32" then
2753 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2755 else if pname
== "to_f" then
2756 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
2758 else if pname
== "&" then
2759 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
2761 else if pname
== "|" then
2762 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
2764 else if pname
== "^" then
2765 v
.ret
(v
.new_expr
("{arguments[0]} ^ {arguments[1]}", ret
.as(not null)))
2767 else if pname
== "unary ~" then
2768 v
.ret
(v
.new_expr
("~{arguments[0]}", ret
.as(not null)))
2771 else if cname
== "Int16" then
2772 if pname
== "output" then
2773 v
.add
("printf(\"%\
"PRIi16 \"\\n\
", {arguments.first});")
2775 else if pname
== "object_id" then
2776 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2778 else if pname
== "+" then
2779 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2781 else if pname
== "-" then
2782 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2784 else if pname
== "unary -" then
2785 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2787 else if pname
== "unary +" then
2790 else if pname
== "*" then
2791 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2793 else if pname
== "/" then
2794 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2796 else if pname
== "%" then
2797 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2799 else if pname
== "<<" then
2800 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2802 else if pname
== ">>" then
2803 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2805 else if pname
== "==" then
2806 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2808 else if pname
== "!=" then
2809 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2810 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2812 else if pname
== "<" then
2813 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2815 else if pname
== ">" then
2816 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2818 else if pname
== "<=" then
2819 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2821 else if pname
== ">=" then
2822 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2824 else if pname
== "to_i" then
2825 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2827 else if pname
== "to_b" then
2828 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2830 else if pname
== "to_i8" then
2831 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
2833 else if pname
== "to_u16" then
2834 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
2836 else if pname
== "to_i32" then
2837 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2839 else if pname
== "to_u32" then
2840 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2842 else if pname
== "to_f" then
2843 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
2845 else if pname
== "&" then
2846 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
2848 else if pname
== "|" then
2849 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
2851 else if pname
== "^" then
2852 v
.ret
(v
.new_expr
("{arguments[0]} ^ {arguments[1]}", ret
.as(not null)))
2854 else if pname
== "unary ~" then
2855 v
.ret
(v
.new_expr
("~{arguments[0]}", ret
.as(not null)))
2858 else if cname
== "UInt16" then
2859 if pname
== "output" then
2860 v
.add
("printf(\"%\
"PRIu16 \"\\n\
", {arguments.first});")
2862 else if pname
== "object_id" then
2863 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2865 else if pname
== "+" then
2866 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2868 else if pname
== "-" then
2869 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2871 else if pname
== "unary -" then
2872 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2874 else if pname
== "unary +" then
2877 else if pname
== "*" then
2878 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2880 else if pname
== "/" then
2881 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2883 else if pname
== "%" then
2884 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2886 else if pname
== "<<" then
2887 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2889 else if pname
== ">>" then
2890 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2892 else if pname
== "==" then
2893 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2895 else if pname
== "!=" then
2896 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2897 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2899 else if pname
== "<" then
2900 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2902 else if pname
== ">" then
2903 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2905 else if pname
== "<=" then
2906 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2908 else if pname
== ">=" then
2909 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2911 else if pname
== "to_i" then
2912 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
2914 else if pname
== "to_b" then
2915 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
2917 else if pname
== "to_i8" then
2918 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
2920 else if pname
== "to_i16" then
2921 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
2923 else if pname
== "to_i32" then
2924 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
2926 else if pname
== "to_u32" then
2927 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
2929 else if pname
== "to_f" then
2930 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
2932 else if pname
== "&" then
2933 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
2935 else if pname
== "|" then
2936 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
2938 else if pname
== "^" then
2939 v
.ret
(v
.new_expr
("{arguments[0]} ^ {arguments[1]}", ret
.as(not null)))
2941 else if pname
== "unary ~" then
2942 v
.ret
(v
.new_expr
("~{arguments[0]}", ret
.as(not null)))
2945 else if cname
== "Int32" then
2946 if pname
== "output" then
2947 v
.add
("printf(\"%\
"PRIi32 \"\\n\
", {arguments.first});")
2949 else if pname
== "object_id" then
2950 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
2952 else if pname
== "+" then
2953 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
2955 else if pname
== "-" then
2956 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
2958 else if pname
== "unary -" then
2959 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
2961 else if pname
== "unary +" then
2964 else if pname
== "*" then
2965 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
2967 else if pname
== "/" then
2968 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
2970 else if pname
== "%" then
2971 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
2973 else if pname
== "<<" then
2974 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
2976 else if pname
== ">>" then
2977 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
2979 else if pname
== "==" then
2980 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
2982 else if pname
== "!=" then
2983 var res
= v
.equal_test
(arguments
[0], arguments
[1])
2984 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
2986 else if pname
== "<" then
2987 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
2989 else if pname
== ">" then
2990 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
2992 else if pname
== "<=" then
2993 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
2995 else if pname
== ">=" then
2996 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
2998 else if pname
== "to_i" then
2999 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
3001 else if pname
== "to_b" then
3002 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
3004 else if pname
== "to_i8" then
3005 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
3007 else if pname
== "to_i16" then
3008 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
3010 else if pname
== "to_u16" then
3011 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
3013 else if pname
== "to_u32" then
3014 v
.ret
(v
.new_expr
("(uint32_t){arguments[0]}", ret
.as(not null)))
3016 else if pname
== "to_f" then
3017 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
3019 else if pname
== "&" then
3020 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
3022 else if pname
== "|" then
3023 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
3025 else if pname
== "^" then
3026 v
.ret
(v
.new_expr
("{arguments[0]} ^ {arguments[1]}", ret
.as(not null)))
3028 else if pname
== "unary ~" then
3029 v
.ret
(v
.new_expr
("~{arguments[0]}", ret
.as(not null)))
3032 else if cname
== "UInt32" then
3033 if pname
== "output" then
3034 v
.add
("printf(\"%\
"PRIu32 \"\\n\
", {arguments.first});")
3036 else if pname
== "object_id" then
3037 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
3039 else if pname
== "+" then
3040 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
3042 else if pname
== "-" then
3043 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
3045 else if pname
== "unary -" then
3046 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
3048 else if pname
== "unary +" then
3051 else if pname
== "*" then
3052 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
3054 else if pname
== "/" then
3055 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
3057 else if pname
== "%" then
3058 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
3060 else if pname
== "<<" then
3061 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
3063 else if pname
== ">>" then
3064 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
3066 else if pname
== "==" then
3067 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
3069 else if pname
== "!=" then
3070 var res
= v
.equal_test
(arguments
[0], arguments
[1])
3071 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
3073 else if pname
== "<" then
3074 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
3076 else if pname
== ">" then
3077 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
3079 else if pname
== "<=" then
3080 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
3082 else if pname
== ">=" then
3083 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
3085 else if pname
== "to_i" then
3086 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
3088 else if pname
== "to_b" then
3089 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
3091 else if pname
== "to_i8" then
3092 v
.ret
(v
.new_expr
("(int8_t){arguments[0]}", ret
.as(not null)))
3094 else if pname
== "to_i16" then
3095 v
.ret
(v
.new_expr
("(int16_t){arguments[0]}", ret
.as(not null)))
3097 else if pname
== "to_u16" then
3098 v
.ret
(v
.new_expr
("(uint16_t){arguments[0]}", ret
.as(not null)))
3100 else if pname
== "to_i32" then
3101 v
.ret
(v
.new_expr
("(int32_t){arguments[0]}", ret
.as(not null)))
3103 else if pname
== "to_f" then
3104 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
3106 else if pname
== "&" then
3107 v
.ret
(v
.new_expr
("{arguments[0]} & {arguments[1]}", ret
.as(not null)))
3109 else if pname
== "|" then
3110 v
.ret
(v
.new_expr
("{arguments[0]} | {arguments[1]}", ret
.as(not null)))
3112 else if pname
== "^" then
3113 v
.ret
(v
.new_expr
("{arguments[0]} ^ {arguments[1]}", ret
.as(not null)))
3115 else if pname
== "unary ~" then
3116 v
.ret
(v
.new_expr
("~{arguments[0]}", ret
.as(not null)))
3120 if pname
== "exit" then
3121 v
.add
("exit((int){arguments[1]});")
3123 else if pname
== "sys" then
3124 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
3126 else if pname
== "object_id" then
3127 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
3129 else if pname
== "is_same_type" then
3130 v
.ret
(v
.is_same_type_test
(arguments
[0], arguments
[1]))
3132 else if pname
== "is_same_instance" then
3133 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
3135 else if pname
== "output_class_name" then
3136 var nat
= v
.class_name_string
(arguments
.first
)
3137 v
.add
("printf(\"%s\\n\
", {nat});")
3139 else if pname
== "native_class_name" then
3140 var nat
= v
.class_name_string
(arguments
.first
)
3141 v
.ret
(v
.new_expr
("(char*){nat}", ret
.as(not null)))
3143 else if pname
== "force_garbage_collection" then
3144 v
.add
("nit_gcollect();")
3146 else if pname
== "native_argc" then
3147 v
.ret
(v
.new_expr
("glob_argc", ret
.as(not null)))
3149 else if pname
== "native_argv" then
3150 v
.ret
(v
.new_expr
("glob_argv[{arguments[1]}]", ret
.as(not null)))
3156 # Compile an extern method
3157 # Return `true` if the compilation was successful, `false` if a fall-back is needed
3158 fun compile_externmeth_to_c
(v
: AbstractCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable]): Bool
3161 var at
= self.get_single_annotation
("extern", v
.compiler
.modelbuilder
)
3162 if at
!= null and at
.n_args
.length
== 1 then
3163 externname
= at
.arg_as_string
(v
.compiler
.modelbuilder
)
3164 if externname
== null then return false
3168 v
.add_extern
(mpropdef
.mclassdef
.mmodule
)
3169 var res
: nullable RuntimeVariable = null
3170 var ret
= mpropdef
.msignature
.return_mtype
3172 ret
= v
.resolve_for
(ret
, arguments
.first
)
3173 res
= v
.new_var_extern
(ret
)
3175 v
.adapt_signature
(mpropdef
, arguments
)
3176 v
.unbox_signature_extern
(mpropdef
, arguments
)
3179 v
.add
("{externname}({arguments.join(", ")});")
3181 v
.add
("{res} = {externname}({arguments.join(", ")});")
3182 res
= v
.box_extern
(res
, ret
.as(not null))
3188 # Compile an extern factory
3189 # Return `true` if the compilation was successful, `false` if a fall-back is needed
3190 fun compile_externinit_to_c
(v
: AbstractCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable]): Bool
3193 var at
= self.get_single_annotation
("extern", v
.compiler
.modelbuilder
)
3195 externname
= at
.arg_as_string
(v
.compiler
.modelbuilder
)
3196 if externname
== null then return false
3200 v
.add_extern
(mpropdef
.mclassdef
.mmodule
)
3201 v
.adapt_signature
(mpropdef
, arguments
)
3202 v
.unbox_signature_extern
(mpropdef
, arguments
)
3203 var ret
= arguments
.first
.mtype
3204 var res
= v
.new_var_extern
(ret
)
3208 v
.add
("{res} = {externname}({arguments.join(", ")});")
3209 res
= v
.box_extern
(res
, ret
)
3215 redef class AAttrPropdef
3216 redef fun can_inline
: Bool do return not is_lazy
3218 redef fun compile_to_c
(v
, mpropdef
, arguments
)
3220 if mpropdef
== mreadpropdef
then
3221 assert arguments
.length
== 1
3222 var recv
= arguments
.first
3226 var ret
= self.mtype
3227 var useiset
= not ret
.is_c_primitive
and not ret
isa MNullableType
3228 var guard
= self.mlazypropdef
.mproperty
3230 set
= v
.isset_attribute
(self.mpropdef
.mproperty
, recv
)
3232 set
= v
.read_attribute
(guard
, recv
)
3234 v
.add
("if(likely({set})) \{")
3235 res
= v
.read_attribute
(self.mpropdef
.mproperty
, recv
)
3238 var value
= evaluate_expr
(v
, recv
)
3240 v
.assign
(res
, value
)
3242 var true_v
= v
.bool_instance
(true)
3243 v
.write_attribute
(guard
, arguments
.first
, true_v
)
3247 res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
3249 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
3250 else if mpropdef
== mwritepropdef
then
3251 assert arguments
.length
== 2
3252 var recv
= arguments
.first
3253 var arg
= arguments
[1]
3254 if is_optional
and v
.maybe_null
(arg
) then
3255 var value
= v
.new_var
(self.mpropdef
.static_mtype
.as(not null))
3256 v
.add
("if ({arg} == NULL) \{")
3257 v
.assign
(value
, evaluate_expr
(v
, recv
))
3259 v
.assign
(value
, arg
)
3263 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arg
)
3265 var ret
= self.mtype
3266 var useiset
= not ret
.is_c_primitive
and not ret
isa MNullableType
3268 v
.write_attribute
(self.mlazypropdef
.mproperty
, arguments
.first
, v
.bool_instance
(true))
3276 fun init_expr
(v
: AbstractCompilerVisitor, recv
: RuntimeVariable)
3278 if has_value
and not is_lazy
and not is_optional
and not n_expr
isa ANullExpr then evaluate_expr
(v
, recv
)
3281 # Evaluate, store and return the default value of the attribute
3282 private fun evaluate_expr
(v
: AbstractCompilerVisitor, recv
: RuntimeVariable): RuntimeVariable
3284 var oldnode
= v
.current_node
3285 v
.current_node
= self
3286 var old_frame
= v
.frame
3287 var frame
= new StaticFrame(v
, self.mreadpropdef
.as(not null), recv
.mcasttype
.undecorate
.as(MClassType), [recv
])
3291 var mtype
= self.mtype
3292 assert mtype
!= null
3294 var nexpr
= self.n_expr
3295 var nblock
= self.n_block
3296 if nexpr
!= null then
3297 value
= v
.expr
(nexpr
, mtype
)
3298 else if nblock
!= null then
3299 value
= v
.new_var
(mtype
)
3300 frame
.returnvar
= value
3301 frame
.returnlabel
= v
.get_name
("RET_LABEL")
3304 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
3310 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
3313 v
.current_node
= oldnode
3318 fun check_expr
(v
: AbstractCompilerVisitor, recv
: RuntimeVariable)
3320 var nexpr
= self.n_expr
3321 if nexpr
!= null then return
3323 var oldnode
= v
.current_node
3324 v
.current_node
= self
3325 var old_frame
= v
.frame
3326 var frame
= new StaticFrame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
3328 # Force read to check the initialization
3329 v
.read_attribute
(self.mpropdef
.mproperty
, recv
)
3331 v
.current_node
= oldnode
3335 redef class AClassdef
3336 private fun compile_to_c
(v
: AbstractCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
3338 if mpropdef
.mproperty
.is_root_init
then
3339 assert arguments
.length
== 1
3340 if not mpropdef
.is_intro
then
3341 v
.supercall
(mpropdef
, arguments
.first
.mtype
.as(MClassType), arguments
)
3351 # Try to compile self as an expression
3352 # Do not call this method directly, use `v.expr` instead
3353 private fun expr
(v
: AbstractCompilerVisitor): nullable RuntimeVariable
3355 v
.add
("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
3356 var mtype
= self.mtype
3357 if mtype
== null then
3360 var res
= v
.new_var
(mtype
)
3361 v
.add
("/* {res} = NOT YET {class_name} */")
3366 # Try to compile self as a statement
3367 # Do not call this method directly, use `v.stmt` instead
3368 private fun stmt
(v
: AbstractCompilerVisitor)
3374 redef class ABlockExpr
3377 for e
in self.n_expr
do v
.stmt
(e
)
3381 var last
= self.n_expr
.last
3382 for e
in self.n_expr
do
3383 if e
== last
then break
3386 return v
.expr
(last
, null)
3390 redef class AVardeclExpr
3393 var variable
= self.variable
.as(not null)
3394 var ne
= self.n_expr
3396 var i
= v
.expr
(ne
, variable
.declared_type
)
3397 v
.assign
(v
.variable
(variable
), i
)
3402 redef class AVarExpr
3405 var res
= v
.variable
(self.variable
.as(not null))
3406 var mtype
= self.mtype
.as(not null)
3407 return v
.autoadapt
(res
, mtype
)
3411 redef class AVarAssignExpr
3414 var variable
= self.variable
.as(not null)
3415 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
3416 v
.assign
(v
.variable
(variable
), i
)
3421 redef class AVarReassignExpr
3424 var variable
= self.variable
.as(not null)
3425 var vari
= v
.variable
(variable
)
3426 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
3427 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [vari
, value
])
3429 v
.assign
(v
.variable
(variable
), res
)
3433 redef class ASelfExpr
3434 redef fun expr
(v
) do return v
.frame
.arguments
.first
3437 redef class AImplicitSelfExpr
3438 redef fun expr
(v
) do
3439 if not is_sys
then return super
3440 return v
.new_expr
("glob_sys", mtype
.as(not null))
3444 redef class AEscapeExpr
3445 redef fun stmt
(v
) do v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
3448 redef class AReturnExpr
3451 var nexpr
= self.n_expr
3452 if nexpr
!= null then
3453 var returnvar
= v
.frame
.returnvar
.as(not null)
3454 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
3455 v
.assign
(returnvar
, i
)
3457 v
.add
("goto {v.frame.returnlabel.as(not null)};")
3461 redef class AAbortExpr
3462 redef fun stmt
(v
) do v
.add_abort
("Aborted")
3468 var cond
= v
.expr_bool
(self.n_expr
)
3469 v
.add
("if ({cond})\{")
3478 var res
= v
.new_var
(self.mtype
.as(not null))
3479 var cond
= v
.expr_bool
(self.n_expr
)
3480 v
.add
("if ({cond})\{")
3481 v
.assign
(res
, v
.expr
(self.n_then
.as(not null), null))
3483 v
.assign
(res
, v
.expr
(self.n_else
.as(not null), null))
3489 redef class AIfexprExpr
3492 var res
= v
.new_var
(self.mtype
.as(not null))
3493 var cond
= v
.expr_bool
(self.n_expr
)
3494 v
.add
("if ({cond})\{")
3495 v
.assign
(res
, v
.expr
(self.n_then
, null))
3497 v
.assign
(res
, v
.expr
(self.n_else
, null))
3506 if self.n_catch
!= null then
3507 v
.add
("catchStack.cursor += 1;")
3508 v
.add
("if(!setjmp(catchStack.envs[catchStack.cursor]))\{")
3509 v
.stmt
(self.n_block
)
3510 v
.add
("catchStack.cursor -= 1;")
3512 v
.add
("catchStack.cursor -= 1;")
3513 v
.stmt
(self.n_catch
)
3516 v
.stmt
(self.n_block
)
3518 v
.add_escape_label
(break_mark
)
3522 redef class AWhileExpr
3526 var cond
= v
.expr_bool
(self.n_expr
)
3527 v
.add
("if (!{cond}) break;")
3528 v
.stmt
(self.n_block
)
3529 v
.add_escape_label
(continue_mark
)
3531 v
.add_escape_label
(break_mark
)
3535 redef class ALoopExpr
3539 v
.stmt
(self.n_block
)
3540 v
.add_escape_label
(continue_mark
)
3542 v
.add_escape_label
(break_mark
)
3546 redef class AForExpr
3549 for g
in n_groups
do
3550 var cl
= v
.expr
(g
.n_expr
, null)
3551 var it_meth
= g
.method_iterator
3552 assert it_meth
!= null
3553 var it
= v
.compile_callsite
(it_meth
, [cl
])
3558 for g
in n_groups
do
3560 var isok_meth
= g
.method_is_ok
3561 assert isok_meth
!= null
3562 var ok
= v
.compile_callsite
(isok_meth
, [it
])
3564 v
.add
("if(!{ok}) break;")
3565 if g
.variables
.length
== 1 then
3566 var item_meth
= g
.method_item
3567 assert item_meth
!= null
3568 var i
= v
.compile_callsite
(item_meth
, [it
])
3570 v
.assign
(v
.variable
(g
.variables
.first
), i
)
3571 else if g
.variables
.length
== 2 then
3572 var key_meth
= g
.method_key
3573 assert key_meth
!= null
3574 var i
= v
.compile_callsite
(key_meth
, [it
])
3576 v
.assign
(v
.variable
(g
.variables
[0]), i
)
3577 var item_meth
= g
.method_item
3578 assert item_meth
!= null
3579 i
= v
.compile_callsite
(item_meth
, [it
])
3581 v
.assign
(v
.variable
(g
.variables
[1]), i
)
3586 v
.stmt
(self.n_block
)
3587 v
.add_escape_label
(continue_mark
)
3588 for g
in n_groups
do
3589 var next_meth
= g
.method_next
3590 assert next_meth
!= null
3591 v
.compile_callsite
(next_meth
, [g
.it
])
3594 v
.add_escape_label
(break_mark
)
3596 for g
in n_groups
do
3597 var method_finish
= g
.method_finish
3598 if method_finish
!= null then
3599 # TODO: Find a way to call this also in long escape (e.g. return)
3600 v
.compile_callsite
(method_finish
, [g
.it
])
3606 redef class AForGroup
3607 # C variable representing the iterator
3608 private var it
: RuntimeVariable is noinit
3611 redef class AAssertExpr
3614 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
3616 var cond
= v
.expr_bool
(self.n_expr
)
3617 v
.add
("if (unlikely(!{cond})) \{")
3624 v
.add_abort
("Assert '{nid.text}' failed")
3626 v
.add_abort
("Assert failed")
3631 # Explain assert if it fails
3632 private fun explain_assert
(v
: AbstractCompilerVisitor)
3634 var explain_assert_str
= explain_assert_str
3635 if explain_assert_str
== null then return
3637 var nas
= v
.compiler
.modelbuilder
.model
.get_mclasses_by_name
("NativeArray")
3638 if nas
== null then return
3640 nas
= v
.compiler
.modelbuilder
.model
.get_mclasses_by_name
("Array")
3641 if nas
== null or nas
.is_empty
then return
3643 var expr
= explain_assert_str
.expr
(v
)
3644 if expr
== null then return
3646 var cstr
= v
.send
(v
.get_property
("to_cstring", expr
.mtype
), [expr
])
3647 if cstr
== null then return
3649 v
.add
"PRINT_ERROR(\"Runtime assert: %s\\n\
", {cstr});"
3656 var res
= v
.new_var
(self.mtype
.as(not null))
3657 var i1
= v
.expr_bool
(self.n_expr
)
3658 v
.add
("if ({i1}) \{")
3661 var i2
= v
.expr_bool
(self.n_expr2
)
3662 v
.add
("{res} = {i2};")
3668 redef class AImpliesExpr
3671 var res
= v
.new_var
(self.mtype
.as(not null))
3672 var i1
= v
.expr_bool
(self.n_expr
)
3673 v
.add
("if (!{i1}) \{")
3676 var i2
= v
.expr_bool
(self.n_expr2
)
3677 v
.add
("{res} = {i2};")
3683 redef class AAndExpr
3686 var res
= v
.new_var
(self.mtype
.as(not null))
3687 var i1
= v
.expr_bool
(self.n_expr
)
3688 v
.add
("if (!{i1}) \{")
3691 var i2
= v
.expr_bool
(self.n_expr2
)
3692 v
.add
("{res} = {i2};")
3698 redef class ANotExpr
3701 var cond
= v
.expr_bool
(self.n_expr
)
3702 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
3706 redef class AOrElseExpr
3709 var res
= v
.new_var
(self.mtype
.as(not null))
3710 var i1
= v
.expr
(self.n_expr
, null)
3712 if not v
.maybe_null
(i1
) then return i1
3714 v
.add
("if ({i1}!=NULL) \{")
3717 var i2
= v
.expr
(self.n_expr2
, null)
3724 redef class AIntegerExpr
3725 redef fun expr
(v
) do
3726 if value
isa Int then return v
.int_instance
(value
.as(Int))
3727 if value
isa Byte then return v
.byte_instance
(value
.as(Byte))
3728 if value
isa Int8 then return v
.int8_instance
(value
.as(Int8))
3729 if value
isa Int16 then return v
.int16_instance
(value
.as(Int16))
3730 if value
isa UInt16 then return v
.uint16_instance
(value
.as(UInt16))
3731 if value
isa Int32 then return v
.int32_instance
(value
.as(Int32))
3732 if value
isa UInt32 then return v
.uint32_instance
(value
.as(UInt32))
3733 # Should never happen
3738 redef class AFloatExpr
3739 redef fun expr
(v
) do return v
.float_instance
("{self.n_float.text}") # FIXME use value, not n_float
3742 redef class ACharExpr
3743 redef fun expr
(v
) do
3744 if is_ascii
then return v
.byte_instance
(value
.as(not null).ascii
)
3745 if is_code_point
then return v
.int_instance
(value
.as(not null).code_point
)
3746 return v
.char_instance
(self.value
.as(not null))
3750 redef class AArrayExpr
3753 var mtype
= self.element_mtype
.as(not null)
3754 var array
= new Array[RuntimeVariable]
3755 var res
= v
.array_instance
(array
, mtype
)
3757 var old_comprehension
= v
.frame
.comprehension
3758 v
.frame
.comprehension
= res
3759 for nexpr
in self.n_exprs
do
3762 v
.frame
.comprehension
= old_comprehension
3768 redef class AugmentedStringFormExpr
3769 # Factorize the making of a `Regex` object from a literal prefixed string
3770 protected fun make_re
(v
: AbstractCompilerVisitor, rs
: RuntimeVariable): nullable RuntimeVariable do
3773 var res
= v
.compile_callsite
(re
, [rs
])
3775 print
"Cannot call property `to_re` on {self}"
3778 for i
in suffix
.chars
do
3780 var ign
= ignore_case
3782 v
.compile_callsite
(ign
, [res
, v
.bool_instance
(true)])
3788 v
.compile_callsite
(nl
, [res
, v
.bool_instance
(true)])
3794 v
.compile_callsite
(ext
, [res
, v
.bool_instance
(false)])
3797 # Should not happen, this needs to be updated
3798 # along with the addition of new suffixes
3805 redef class AStringFormExpr
3806 redef fun expr
(v
) do return v
.string_instance
(value
)
3809 redef class AStringExpr
3810 redef fun expr
(v
) do
3811 var s
= v
.string_instance
(value
)
3812 if is_string
then return s
3813 if is_bytestring
then
3814 var ns
= v
.c_string_instance
(bytes
.items
, bytes
.length
)
3815 var ln
= v
.int_instance
(bytes
.length
)
3816 var cs
= to_bytes_with_copy
3818 var res
= v
.compile_callsite
(cs
, [ns
, ln
])
3822 var res
= make_re
(v
, s
)
3826 print
"Unimplemented prefix or suffix for {self}"
3833 redef class ASuperstringExpr
3836 var type_string
= v
.mmodule
.string_type
3838 # Collect elements of the superstring
3839 var array
= new Array[AExpr]
3840 for ne
in self.n_exprs
do
3841 # Drop literal empty string.
3842 # They appears in things like "{a}" that is ["", a, ""]
3843 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
3847 # Store the allocated native array in a static variable
3849 var varonce
= v
.get_name
("varonce")
3850 v
.add
("if (unlikely({varonce}==NULL)) \{")
3852 # The native array that will contains the elements to_s-ized.
3853 # For fast concatenation.
3854 var a
= v
.native_array_instance
(type_string
, v
.int_instance
(array
.length
))
3856 v
.add_decl
("static {a.mtype.ctype} {varonce};")
3858 # Pre-fill the array with the literal string parts.
3859 # So they do not need to be filled again when reused
3860 for i
in [0..array
.length
[ do
3862 if not ne
isa AStringFormExpr then continue
3863 var e
= v
.expr
(ne
, null)
3864 v
.native_array_set
(a
, i
, e
)
3868 # Take the native-array from the store.
3869 # The point is to prevent that some recursive execution use (and corrupt) the same native array
3870 # WARNING: not thread safe! (FIXME?)
3871 v
.add
("{a} = {varonce};")
3872 v
.add
("{varonce} = NULL;")
3875 # Stringify the elements and put them in the native array
3876 var to_s_method
= v
.get_property
("to_s", v
.object_type
)
3877 for i
in [0..array
.length
[ do
3879 if ne
isa AStringFormExpr then continue
3880 var e
= v
.expr
(ne
, null)
3881 # Skip the `to_s` if the element is already a String
3882 if not e
.mcasttype
.is_subtype
(v
.compiler
.mainmodule
, null, type_string
) then
3883 e
= v
.send
(to_s_method
, [e
]).as(not null)
3885 v
.native_array_set
(a
, i
, e
)
3888 # Fast join the C string to get the result
3889 var res
= v
.send
(v
.get_property
("native_to_s", a
.mtype
), [a
])
3892 if is_re
then res
= make_re
(v
, res
)
3894 # We finish to work with the native array,
3895 # so store it so that it can be reused
3896 v
.add
("{varonce} = {a};")
3902 redef class ACrangeExpr
3905 var i1
= v
.expr
(self.n_expr
, null)
3906 var i2
= v
.expr
(self.n_expr2
, null)
3907 var mtype
= self.mtype
.as(MClassType)
3908 var res
= v
.init_instance
(mtype
)
3909 v
.compile_callsite
(init_callsite
.as(not null), [res
, i1
, i2
])
3914 redef class AOrangeExpr
3917 var i1
= v
.expr
(self.n_expr
, null)
3918 var i2
= v
.expr
(self.n_expr2
, null)
3919 var mtype
= self.mtype
.as(MClassType)
3920 var res
= v
.init_instance
(mtype
)
3921 v
.compile_callsite
(init_callsite
.as(not null), [res
, i1
, i2
])
3926 redef class ATrueExpr
3927 redef fun expr
(v
) do return v
.bool_instance
(true)
3930 redef class AFalseExpr
3931 redef fun expr
(v
) do return v
.bool_instance
(false)
3934 redef class ANullExpr
3935 redef fun expr
(v
) do return v
.null_instance
3938 redef class AIsaExpr
3941 var i
= v
.expr
(self.n_expr
, null)
3942 var cast_type
= self.cast_type
3943 if cast_type
== null then return null # no-no on broken node
3944 return v
.type_test
(i
, cast_type
, "isa")
3948 redef class AAsCastExpr
3951 var i
= v
.expr
(self.n_expr
, null)
3952 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
3954 v
.add_cast
(i
, self.mtype
.as(not null), "as")
3959 redef class AAsNotnullExpr
3962 var i
= v
.expr
(self.n_expr
, null)
3963 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
3965 if not v
.maybe_null
(i
) then return i
3967 v
.add
("if (unlikely({i} == NULL)) \{")
3968 v
.add_abort
("Cast failed")
3974 redef class AParExpr
3975 redef fun expr
(v
) do return v
.expr
(self.n_expr
, null)
3978 redef class AOnceExpr
3981 var mtype
= self.mtype
.as(not null)
3982 var name
= v
.get_name
("varonce")
3983 var guard
= v
.get_name
(name
+ "_guard")
3984 v
.add_decl
("static {mtype.ctype} {name};")
3985 v
.add_decl
("static int {guard};")
3986 var res
= v
.new_var
(mtype
)
3987 v
.add
("if (likely({guard})) \{")
3988 v
.add
("{res} = {name};")
3990 var i
= v
.expr
(self.n_expr
, mtype
)
3991 v
.add
("{res} = {i};")
3992 v
.add
("{name} = {res};")
3993 v
.add
("{guard} = 1;")
3999 redef class ASendExpr
4002 var recv
= v
.expr
(self.n_expr
, null)
4003 var callsite
= self.callsite
.as(not null)
4004 if callsite
.is_broken
then return null
4005 var args
= v
.varargize
(callsite
.mpropdef
, callsite
.signaturemap
, recv
, self.raw_arguments
)
4006 return v
.compile_callsite
(callsite
, args
)
4010 redef class ASendReassignFormExpr
4013 var recv
= v
.expr
(self.n_expr
, null)
4014 var callsite
= self.callsite
.as(not null)
4015 if callsite
.is_broken
then return
4016 var args
= v
.varargize
(callsite
.mpropdef
, callsite
.signaturemap
, recv
, self.raw_arguments
)
4018 var value
= v
.expr
(self.n_value
, null)
4020 var left
= v
.compile_callsite
(callsite
, args
)
4023 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [left
, value
])
4027 v
.compile_callsite
(self.write_callsite
.as(not null), args
)
4031 redef class ASuperExpr
4034 var frame
= v
.frame
.as(not null)
4035 var recv
= frame
.arguments
.first
4037 var callsite
= self.callsite
4038 if callsite
!= null then
4039 if callsite
.is_broken
then return null
4042 if self.n_args
.n_exprs
.is_empty
then
4043 # Add automatic arguments for the super init call
4045 for i
in [0..callsite
.msignature
.arity
[ do
4046 args
.add
(frame
.arguments
[i
+1])
4049 args
= v
.varargize
(callsite
.mpropdef
, callsite
.signaturemap
, recv
, self.n_args
.n_exprs
)
4053 var res
= v
.compile_callsite
(callsite
, args
)
4057 var mpropdef
= self.mpropdef
.as(not null)
4060 if self.n_args
.n_exprs
.is_empty
then
4061 args
= frame
.arguments
4063 args
= v
.varargize
(mpropdef
, signaturemap
, recv
, self.n_args
.n_exprs
)
4066 # Standard call-next-method
4067 return v
.supercall
(mpropdef
, recv
.mtype
.as(MClassType), args
)
4071 redef class ANewExpr
4074 var mtype
= self.recvtype
4075 assert mtype
!= null
4077 if mtype
.mclass
.name
== "NativeArray" then
4078 assert self.n_args
.n_exprs
.length
== 1
4079 var l
= v
.expr
(self.n_args
.n_exprs
.first
, null)
4080 assert mtype
isa MGenericType
4081 var elttype
= mtype
.arguments
.first
4082 return v
.native_array_instance
(elttype
, l
)
4085 var callsite
= self.callsite
4086 if callsite
== null then return v
.init_instance_or_extern
(mtype
)
4087 if callsite
.is_broken
then return null
4090 # new factories are badly implemented.
4091 # They assume a stub temporary receiver exists.
4092 # This temporary receiver is required because it
4093 # currently holds the method and the formal types.
4095 # However, this object could be reused if the formal types are the same.
4096 # Therefore, the following code will `once` it in these case
4097 if callsite
.mproperty
.is_new
and not mtype
.need_anchor
then
4098 var name
= v
.get_name
("varoncenew")
4099 var guard
= v
.get_name
(name
+ "_guard")
4100 v
.add_decl
("static {mtype.ctype} {name};")
4101 v
.add_decl
("static int {guard};")
4102 recv
= v
.new_var
(mtype
)
4103 v
.add
("if (likely({guard})) \{")
4104 v
.add
("{recv} = {name};")
4106 var i
= v
.init_instance_or_extern
(mtype
)
4107 v
.add
("{recv} = {i};")
4108 v
.add
("{name} = {recv};")
4109 v
.add
("{guard} = 1;")
4112 recv
= v
.init_instance_or_extern
(mtype
)
4115 var args
= v
.varargize
(callsite
.mpropdef
, callsite
.signaturemap
, recv
, self.n_args
.n_exprs
)
4116 var res2
= v
.compile_callsite
(callsite
, args
)
4117 if res2
!= null then
4118 #self.debug("got {res2} from {mproperty}. drop {recv}")
4125 redef class AAttrExpr
4128 var recv
= v
.expr
(self.n_expr
, null)
4129 var mproperty
= self.mproperty
.as(not null)
4130 return v
.read_attribute
(mproperty
, recv
)
4134 redef class AAttrAssignExpr
4137 var recv
= v
.expr
(self.n_expr
, null)
4138 var i
= v
.expr
(self.n_value
, null)
4139 var mproperty
= self.mproperty
.as(not null)
4140 v
.write_attribute
(mproperty
, recv
, i
)
4145 redef class AAttrReassignExpr
4148 var recv
= v
.expr
(self.n_expr
, null)
4149 var value
= v
.expr
(self.n_value
, null)
4150 var mproperty
= self.mproperty
.as(not null)
4151 var attr
= v
.read_attribute
(mproperty
, recv
)
4152 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [attr
, value
])
4154 v
.write_attribute
(mproperty
, recv
, res
)
4158 redef class AIssetAttrExpr
4161 var recv
= v
.expr
(self.n_expr
, null)
4162 var mproperty
= self.mproperty
.as(not null)
4163 return v
.isset_attribute
(mproperty
, recv
)
4167 redef class AVarargExpr
4170 return v
.expr
(self.n_expr
, null)
4174 redef class ANamedargExpr
4177 return v
.expr
(self.n_expr
, null)
4181 redef class ADebugTypeExpr
4190 redef class Array[E
]
4191 # Return a new `Array` with the elements only contened in self and not in `o`
4192 fun -(o
: Array[E
]): Array[E
] do
4193 var res
= new Array[E
]
4194 for e
in self do if not o
.has
(e
) then res
.add
(e
)
4200 # All `MProperty` associated to all `MClassDef` of `mclass`
4201 fun properties
(mclass
: MClass): Set[MProperty] do
4202 if not self.properties_cache
.has_key
(mclass
) then
4203 var properties
= new HashSet[MProperty]
4204 var parents
= new Array[MClass]
4205 if self.flatten_mclass_hierarchy
.has
(mclass
) then
4206 parents
.add_all
(mclass
.in_hierarchy
(self).direct_greaters
)
4208 for parent
in parents
do
4209 properties
.add_all
(self.properties
(parent
))
4211 for mclassdef
in mclass
.mclassdefs
do
4212 if not self.in_importation
<= mclassdef
.mmodule
then continue
4213 for mprop
in mclassdef
.intro_mproperties
do
4214 properties
.add
(mprop
)
4217 self.properties_cache
[mclass
] = properties
4219 return properties_cache
[mclass
]
4221 private var properties_cache
: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
4223 # Write FFI and nitni results to file
4224 fun finalize_ffi
(c
: AbstractCompiler) do end
4226 # Give requided addinional system libraries (as given to LD_LIBS)
4227 # Note: can return null instead of an empty set
4228 fun collect_linker_libs
: nullable Array[String] do return null
4231 # Create a tool context to handle options and paths
4232 var toolcontext
= new ToolContext
4234 toolcontext
.tooldescription
= "Usage: nitc [OPTION]... file.nit...\nCompiles Nit programs."
4236 # We do not add other options, so process them now!
4237 toolcontext
.process_options
(args
)
4239 # We need a model to collect stufs
4240 var model
= new Model
4241 # An a model builder to parse files
4242 var modelbuilder
= new ModelBuilder(model
, toolcontext
)
4244 var arguments
= toolcontext
.option_context
.rest
4245 if toolcontext
.opt_run
.value
then
4246 # When --run, only the first is the program, the rest is the run arguments
4247 arguments
= [toolcontext
.option_context
.rest
.shift
]
4249 if arguments
.length
> 1 and toolcontext
.opt_output
.value
!= null then
4250 print
"Option Error: --output needs a single source file. Do you prefer --dir?"
4254 # Here we load an process all modules passed on the command line
4255 var mmodules
= modelbuilder
.parse
(arguments
)
4257 if mmodules
.is_empty
then toolcontext
.quit
4259 modelbuilder
.run_phases
4261 for mmodule
in mmodules
do
4262 toolcontext
.info
("*** PROCESS {mmodule} ***", 1)
4264 toolcontext
.run_global_phases
(ms
)