model: promote `c_name` from abstract-compiler to model
[nit.git] / src / compiler / abstract_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Abstract compiler
18 module abstract_compiler
19
20 import literal
21 import semantize
22 import platform
23 import c_tools
24 private import annotation
25 import mixin
26
27 # Add compiling options
28 redef class ToolContext
29 # --output
30 var opt_output = new OptionString("Output file", "-o", "--output")
31 # --dir
32 var opt_dir = new OptionString("Output directory", "--dir")
33 # --no-cc
34 var opt_no_cc = new OptionBool("Do not invoke C compiler", "--no-cc")
35 # --no-main
36 var opt_no_main = new OptionBool("Do not generate main entry point", "--no-main")
37 # --make-flags
38 var opt_make_flags = new OptionString("Additional options to make", "--make-flags")
39 # --max-c-lines
40 var opt_max_c_lines = new OptionInt("Maximum number of lines in generated C files. Use 0 for unlimited", 10000, "--max-c-lines")
41 # --group-c-files
42 var opt_group_c_files = new OptionBool("Group all generated code in the same series of files", "--group-c-files")
43 # --compile-dir
44 var opt_compile_dir = new OptionString("Directory used to generate temporary files", "--compile-dir")
45 # --hardening
46 var opt_hardening = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
47 # --no-check-covariance
48 var opt_no_check_covariance = new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
49 # --no-check-attr-isset
50 var opt_no_check_attr_isset = new OptionBool("Disable isset tests before each attribute access (dangerous)", "--no-check-attr-isset")
51 # --no-check-assert
52 var opt_no_check_assert = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
53 # --no-check-autocast
54 var opt_no_check_autocast = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
55 # --no-check-null
56 var opt_no_check_null = new OptionBool("Disable tests of null receiver (dangerous)", "--no-check-null")
57 # --no-check-all
58 var opt_no_check_all = new OptionBool("Disable all tests (dangerous)", "--no-check-all")
59 # --typing-test-metrics
60 var opt_typing_test_metrics = new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
61 # --invocation-metrics
62 var opt_invocation_metrics = new OptionBool("Enable static and dynamic count of all method invocations", "--invocation-metrics")
63 # --isset-checks-metrics
64 var opt_isset_checks_metrics = new OptionBool("Enable static and dynamic count of isset checks before attributes access", "--isset-checks-metrics")
65 # --stacktrace
66 var opt_stacktrace = new OptionString("Control the generation of stack traces", "--stacktrace")
67 # --no-gcc-directives
68 var opt_no_gcc_directive = new OptionArray("Disable a advanced gcc directives for optimization", "--no-gcc-directive")
69 # --release
70 var opt_release = new OptionBool("Compile in release mode and finalize application", "--release")
71
72 redef init
73 do
74 super
75 self.option_context.add_option(self.opt_output, self.opt_dir, self.opt_no_cc, self.opt_no_main, self.opt_make_flags, self.opt_compile_dir, self.opt_hardening)
76 self.option_context.add_option(self.opt_no_check_covariance, self.opt_no_check_attr_isset, self.opt_no_check_assert, self.opt_no_check_autocast, self.opt_no_check_null, self.opt_no_check_all)
77 self.option_context.add_option(self.opt_typing_test_metrics, self.opt_invocation_metrics, self.opt_isset_checks_metrics)
78 self.option_context.add_option(self.opt_stacktrace)
79 self.option_context.add_option(self.opt_no_gcc_directive)
80 self.option_context.add_option(self.opt_release)
81 self.option_context.add_option(self.opt_max_c_lines, self.opt_group_c_files)
82
83 opt_no_main.hidden = true
84 end
85
86 redef fun process_options(args)
87 do
88 super
89
90 var st = opt_stacktrace.value
91 if st == "none" or st == "libunwind" or st == "nitstack" then
92 # Fine, do nothing
93 else if st == "auto" or st == null then
94 # Default is nitstack
95 opt_stacktrace.value = "nitstack"
96 else
97 print "Error: unknown value `{st}` for --stacktrace. Use `none`, `libunwind`, `nitstack` or `auto`."
98 exit(1)
99 end
100
101 if opt_output.value != null and opt_dir.value != null then
102 print "Error: cannot use both --dir and --output"
103 exit(1)
104 end
105
106 if opt_no_check_all.value then
107 opt_no_check_covariance.value = true
108 opt_no_check_attr_isset.value = true
109 opt_no_check_assert.value = true
110 opt_no_check_autocast.value = true
111 opt_no_check_null.value = true
112 end
113 end
114 end
115
116 redef class ModelBuilder
117 # The compilation directory
118 var compile_dir: String
119
120 # Simple indirection to `Toolchain::write_and_make`
121 protected fun write_and_make(compiler: AbstractCompiler)
122 do
123 var platform = compiler.mainmodule.target_platform
124 var toolchain
125 if platform == null then
126 toolchain = new MakefileToolchain(toolcontext)
127 else
128 toolchain = platform.toolchain(toolcontext)
129 end
130 compile_dir = toolchain.compile_dir
131 toolchain.write_and_make compiler
132 end
133 end
134
135 redef class Platform
136 fun toolchain(toolcontext: ToolContext): Toolchain is abstract
137 end
138
139 class Toolchain
140 var toolcontext: ToolContext
141
142 fun compile_dir: String
143 do
144 var compile_dir = toolcontext.opt_compile_dir.value
145 if compile_dir == null then compile_dir = ".nit_compile"
146 return compile_dir
147 end
148
149 fun write_and_make(compiler: AbstractCompiler) is abstract
150 end
151
152 class MakefileToolchain
153 super Toolchain
154
155 redef fun write_and_make(compiler)
156 do
157 var compile_dir = compile_dir
158
159 # Generate the .h and .c files
160 # A single C file regroups many compiled rumtime functions
161 # Note that we do not try to be clever an a small change in a Nit source file may change the content of all the generated .c files
162 var time0 = get_time
163 self.toolcontext.info("*** WRITING C ***", 1)
164
165 compile_dir.mkdir
166
167 var cfiles = new Array[String]
168 write_files(compiler, compile_dir, cfiles)
169
170 # Generate the Makefile
171
172 write_makefile(compiler, compile_dir, cfiles)
173
174 var time1 = get_time
175 self.toolcontext.info("*** END WRITING C: {time1-time0} ***", 2)
176
177 # Execute the Makefile
178
179 if self.toolcontext.opt_no_cc.value then return
180
181 time0 = time1
182 self.toolcontext.info("*** COMPILING C ***", 1)
183
184 compile_c_code(compiler, compile_dir)
185
186 time1 = get_time
187 self.toolcontext.info("*** END COMPILING C: {time1-time0} ***", 2)
188 end
189
190 fun write_files(compiler: AbstractCompiler, compile_dir: String, cfiles: Array[String])
191 do
192 var platform = compiler.mainmodule.target_platform
193 if self.toolcontext.opt_stacktrace.value == "nitstack" and (platform == null or platform.supports_libunwind) then compiler.build_c_to_nit_bindings
194 var cc_opt_with_libgc = "-DWITH_LIBGC"
195 if platform != null and not platform.supports_libgc then cc_opt_with_libgc = ""
196
197 # Add gc_choser.h to aditionnal bodies
198 var gc_chooser = new ExternCFile("gc_chooser.c", cc_opt_with_libgc)
199 if cc_opt_with_libgc != "" then gc_chooser.pkgconfigs.add "bdw-gc"
200 compiler.extern_bodies.add(gc_chooser)
201 var clib = toolcontext.nit_dir / "clib"
202 compiler.files_to_copy.add "{clib}/gc_chooser.c"
203 compiler.files_to_copy.add "{clib}/gc_chooser.h"
204
205 # FFI
206 for m in compiler.mainmodule.in_importation.greaters do
207 compiler.finalize_ffi_for_module(m)
208 end
209
210 # Copy original .[ch] files to compile_dir
211 for src in compiler.files_to_copy do
212 var basename = src.basename("")
213 var dst = "{compile_dir}/{basename}"
214 src.file_copy_to dst
215 end
216
217 var hfilename = compiler.header.file.name + ".h"
218 var hfilepath = "{compile_dir}/{hfilename}"
219 var h = new OFStream.open(hfilepath)
220 for l in compiler.header.decl_lines do
221 h.write l
222 h.write "\n"
223 end
224 for l in compiler.header.lines do
225 h.write l
226 h.write "\n"
227 end
228 h.close
229
230 var max_c_lines = toolcontext.opt_max_c_lines.value
231 for f in compiler.files do
232 var i = 0
233 var count = 0
234 var file: nullable OFStream = null
235 for vis in f.writers do
236 if vis == compiler.header then continue
237 var total_lines = vis.lines.length + vis.decl_lines.length
238 if total_lines == 0 then continue
239 count += total_lines
240 if file == null or (count > max_c_lines and max_c_lines > 0) then
241 i += 1
242 if file != null then file.close
243 var cfilename = "{f.name}.{i}.c"
244 var cfilepath = "{compile_dir}/{cfilename}"
245 self.toolcontext.info("new C source files to compile: {cfilepath}", 3)
246 cfiles.add(cfilename)
247 file = new OFStream.open(cfilepath)
248 file.write "#include \"{f.name}.0.h\"\n"
249 count = total_lines
250 end
251 for l in vis.decl_lines do
252 file.write l
253 file.write "\n"
254 end
255 for l in vis.lines do
256 file.write l
257 file.write "\n"
258 end
259 end
260 if file == null then continue
261 file.close
262
263 var cfilename = "{f.name}.0.h"
264 var cfilepath = "{compile_dir}/{cfilename}"
265 var hfile: nullable OFStream = null
266 hfile = new OFStream.open(cfilepath)
267 hfile.write "#include \"{hfilename}\"\n"
268 for key in f.required_declarations do
269 if not compiler.provided_declarations.has_key(key) then
270 var node = compiler.requirers_of_declarations.get_or_null(key)
271 if node != null then
272 node.debug "No provided declaration for {key}"
273 else
274 print "No provided declaration for {key}"
275 end
276 abort
277 end
278 hfile.write compiler.provided_declarations[key]
279 hfile.write "\n"
280 end
281 hfile.close
282 end
283
284 self.toolcontext.info("Total C source files to compile: {cfiles.length}", 2)
285 end
286
287 fun makefile_name(mainmodule: MModule): String do return "{mainmodule.c_name}.mk"
288
289 fun default_outname(mainmodule: MModule): String
290 do
291 # Search a non fictive module
292 var res = mainmodule.name
293 while mainmodule.is_fictive do
294 mainmodule = mainmodule.in_importation.direct_greaters.first
295 res = mainmodule.name
296 end
297 return res
298 end
299
300 # Combine options and platform informations to get the final path of the outfile
301 fun outfile(mainmodule: MModule): String
302 do
303 var res = self.toolcontext.opt_output.value
304 if res != null then return res
305 res = default_outname(mainmodule)
306 var dir = self.toolcontext.opt_dir.value
307 if dir != null then return dir.join_path(res)
308 return res
309 end
310
311 fun write_makefile(compiler: AbstractCompiler, compile_dir: String, cfiles: Array[String])
312 do
313 var mainmodule = compiler.mainmodule
314 var platform = compiler.mainmodule.target_platform
315
316 var outname = outfile(mainmodule)
317
318 var real_outpath = compile_dir.relpath(outname)
319 var outpath = real_outpath.escape_to_mk
320 if outpath != real_outpath then
321 # If the name is crazy and need escaping, we will do an indirection
322 # 1. generate the binary in the .nit_compile dir under an escaped name
323 # 2. copy the binary at the right place in the `all` goal.
324 outpath = mainmodule.c_name
325 end
326 var makename = makefile_name(mainmodule)
327 var makepath = "{compile_dir}/{makename}"
328 var makefile = new OFStream.open(makepath)
329
330 var linker_options = new HashSet[String]
331 for m in mainmodule.in_importation.greaters do
332 var libs = m.collect_linker_libs
333 if libs != null then linker_options.add_all(libs)
334 end
335
336 makefile.write("CC = ccache cc\nCXX = ccache c++\nCFLAGS = -g -O2 -Wno-unused-value -Wno-switch -Wno-attributes\nCINCL =\nLDFLAGS ?= \nLDLIBS ?= -lm {linker_options.join(" ")}\n\n")
337
338 var ost = toolcontext.opt_stacktrace.value
339 if (ost == "libunwind" or ost == "nitstack") and (platform == null or platform.supports_libunwind) then makefile.write("NEED_LIBUNWIND := YesPlease\n")
340
341 # Dynamic adaptations
342 # While `platform` enable complex toolchains, they are statically applied
343 # For a dynamic adaptsation of the compilation, the generated Makefile should check and adapt things itself
344
345 # Check and adapt the targeted system
346 makefile.write("uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n")
347 makefile.write("ifeq ($(uname_S),Darwin)\n")
348 # remove -lunwind since it is already included on macosx
349 makefile.write("\tNEED_LIBUNWIND :=\n")
350 makefile.write("endif\n\n")
351
352 # Check and adapt for the compiler used
353 # clang need an additionnal `-Qunused-arguments`
354 makefile.write("clang_check := $(shell sh -c '$(CC) -v 2>&1 | grep -q clang; echo $$?')\nifeq ($(clang_check), 0)\n\tCFLAGS += -Qunused-arguments\nendif\n")
355
356 makefile.write("ifdef NEED_LIBUNWIND\n\tLDLIBS += -lunwind\nendif\n")
357
358 makefile.write("all: {outpath}\n")
359 if outpath != real_outpath then
360 makefile.write("\tcp -- {outpath.escape_to_sh} {real_outpath.escape_to_sh.replace("$","$$")}")
361 end
362 makefile.write("\n")
363
364 var ofiles = new Array[String]
365 var dep_rules = new Array[String]
366 # Compile each generated file
367 for f in cfiles do
368 var o = f.strip_extension(".c") + ".o"
369 makefile.write("{o}: {f}\n\t$(CC) $(CFLAGS) $(CINCL) -c -o {o} {f}\n\n")
370 ofiles.add(o)
371 dep_rules.add(o)
372 end
373
374 var java_files = new Array[ExternFile]
375
376 var pkgconfigs = new Array[String]
377 for f in compiler.extern_bodies do
378 pkgconfigs.add_all f.pkgconfigs
379 end
380 # Protect pkg-config
381 if not pkgconfigs.is_empty then
382 makefile.write """
383 # does pkg-config exists?
384 ifneq ($(shell which pkg-config >/dev/null; echo $$?), 0)
385 $(error "Command `pkg-config` not found. Please install it")
386 endif
387 """
388 for p in pkgconfigs do
389 makefile.write """
390 # Check for library {{{p}}}
391 ifneq ($(shell pkg-config --exists '{{{p}}}'; echo $$?), 0)
392 $(error "pkg-config: package {{{p}}} is not found.")
393 endif
394 """
395 end
396 end
397
398 # Compile each required extern body into a specific .o
399 for f in compiler.extern_bodies do
400 var o = f.makefile_rule_name
401 var ff = f.filename.basename("")
402 makefile.write("{o}: {ff}\n")
403 makefile.write("\t{f.makefile_rule_content}\n\n")
404 dep_rules.add(f.makefile_rule_name)
405
406 if f.compiles_to_o_file then ofiles.add(o)
407 if f.add_to_jar then java_files.add(f)
408 end
409
410 if not java_files.is_empty then
411 var jar_file = "{outpath}.jar"
412
413 var class_files_array = new Array[String]
414 for f in java_files do class_files_array.add(f.makefile_rule_name)
415 var class_files = class_files_array.join(" ")
416
417 makefile.write("{jar_file}: {class_files}\n")
418 makefile.write("\tjar cf {jar_file} {class_files}\n\n")
419 dep_rules.add jar_file
420 end
421
422 # Link edition
423 var pkg = ""
424 if not pkgconfigs.is_empty then
425 pkg = "`pkg-config --libs {pkgconfigs.join(" ")}`"
426 end
427 makefile.write("{outpath}: {dep_rules.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outpath.escape_to_sh} {ofiles.join(" ")} $(LDLIBS) {pkg}\n\n")
428 # Clean
429 makefile.write("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n")
430 if outpath != real_outpath then
431 makefile.write("\trm -- {outpath.escape_to_sh} 2>/dev/null\n")
432 end
433 makefile.close
434 self.toolcontext.info("Generated makefile: {makepath}", 2)
435
436 makepath.file_copy_to "{compile_dir}/Makefile"
437 end
438
439 fun compile_c_code(compiler: AbstractCompiler, compile_dir: String)
440 do
441 var makename = makefile_name(compiler.mainmodule)
442
443 var makeflags = self.toolcontext.opt_make_flags.value
444 if makeflags == null then makeflags = ""
445 self.toolcontext.info("make -B -C {compile_dir} -f {makename} -j 4 {makeflags}", 2)
446
447 var res
448 if self.toolcontext.verbose_level >= 3 then
449 res = sys.system("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1")
450 else
451 res = sys.system("make -B -C {compile_dir} -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
452 end
453 if res != 0 then
454 toolcontext.error(null, "make failed! Error code: {res}.")
455 end
456 end
457 end
458
459 # Singleton that store the knowledge about the compilation process
460 abstract class AbstractCompiler
461 type VISITOR: AbstractCompilerVisitor
462
463 # Table corresponding c_names to nit names (methods)
464 var names = new HashMap[String, String]
465
466 # The main module of the program currently compiled
467 # Is assigned during the separate compilation
468 var mainmodule: MModule is writable
469
470 # The real main module of the program
471 var realmainmodule: MModule is noinit
472
473 # The modelbuilder used to know the model and the AST
474 var modelbuilder: ModelBuilder is protected writable
475
476 # Is hardening asked? (see --hardening)
477 fun hardening: Bool do return self.modelbuilder.toolcontext.opt_hardening.value
478
479 init
480 do
481 self.realmainmodule = mainmodule
482 end
483
484 # Force the creation of a new file
485 # The point is to avoid contamination between must-be-compiled-separately files
486 fun new_file(name: String): CodeFile
487 do
488 if modelbuilder.toolcontext.opt_group_c_files.value then
489 if self.files.is_empty then
490 var f = new CodeFile(mainmodule.c_name)
491 self.files.add(f)
492 end
493 return self.files.first
494 end
495 var f = new CodeFile(name)
496 self.files.add(f)
497 return f
498 end
499
500 # The list of all associated files
501 # Used to generate .c files
502 var files = new List[CodeFile]
503
504 # Initialize a visitor specific for a compiler engine
505 fun new_visitor: VISITOR is abstract
506
507 # Where global declaration are stored (the main .h)
508 var header: CodeWriter is writable, noinit
509
510 # Provide a declaration that can be requested (before or latter) by a visitor
511 fun provide_declaration(key: String, s: String)
512 do
513 if self.provided_declarations.has_key(key) then
514 assert self.provided_declarations[key] == s
515 end
516 self.provided_declarations[key] = s
517 end
518
519 private var provided_declarations = new HashMap[String, String]
520
521 private var requirers_of_declarations = new HashMap[String, ANode]
522
523 # Builds the .c and .h files to be used when generating a Stack Trace
524 # Binds the generated C function names to Nit function names
525 fun build_c_to_nit_bindings
526 do
527 var compile_dir = modelbuilder.compile_dir
528
529 var stream = new OFStream.open("{compile_dir}/c_functions_hash.c")
530 stream.write("#include <string.h>\n")
531 stream.write("#include <stdlib.h>\n")
532 stream.write("#include \"c_functions_hash.h\"\n")
533 stream.write("typedef struct C_Nit_Names\{char* name; char* nit_name;\}C_Nit_Names;\n")
534 stream.write("const char* get_nit_name(register const char* procproc, register unsigned int len)\{\n")
535 stream.write("char* procname = malloc(len+1);")
536 stream.write("memcpy(procname, procproc, len);")
537 stream.write("procname[len] = '\\0';")
538 stream.write("static const C_Nit_Names map[{names.length}] = \{\n")
539 for i in names.keys do
540 stream.write("\{\"")
541 stream.write(i.escape_to_c)
542 stream.write("\",\"")
543 stream.write(names[i].escape_to_c)
544 stream.write("\"\},\n")
545 end
546 stream.write("\};\n")
547 stream.write("int i;")
548 stream.write("for(i = 0; i < {names.length}; i++)\{")
549 stream.write("if(strcmp(procname,map[i].name) == 0)\{")
550 stream.write("free(procname);")
551 stream.write("return map[i].nit_name;")
552 stream.write("\}")
553 stream.write("\}")
554 stream.write("free(procname);")
555 stream.write("return NULL;")
556 stream.write("\}\n")
557 stream.close
558
559 stream = new OFStream.open("{compile_dir}/c_functions_hash.h")
560 stream.write("const char* get_nit_name(register const char* procname, register unsigned int len);\n")
561 stream.close
562
563 extern_bodies.add(new ExternCFile("{compile_dir}/c_functions_hash.c", ""))
564 end
565
566 # Compile C headers
567 # This method call compile_header_strucs method that has to be refined
568 fun compile_header do
569 self.header.add_decl("#include <stdlib.h>")
570 self.header.add_decl("#include <stdio.h>")
571 self.header.add_decl("#include <string.h>")
572 self.header.add_decl("#include \"gc_chooser.h\"")
573 self.header.add_decl("#ifdef ANDROID")
574 self.header.add_decl(" #include <android/log.h>")
575 self.header.add_decl(" #define PRINT_ERROR(...) (void)__android_log_print(ANDROID_LOG_WARN, \"Nit\", __VA_ARGS__)")
576 self.header.add_decl("#else")
577 self.header.add_decl(" #define PRINT_ERROR(...) fprintf(stderr, __VA_ARGS__)")
578 self.header.add_decl("#endif")
579
580 compile_header_structs
581 compile_nitni_structs
582
583 var gccd_disable = modelbuilder.toolcontext.opt_no_gcc_directive.value
584 if gccd_disable.has("noreturn") or gccd_disable.has("all") then
585 # Signal handler function prototype
586 self.header.add_decl("void show_backtrace(int);")
587 else
588 self.header.add_decl("void show_backtrace(int) __attribute__ ((noreturn));")
589 end
590
591 if gccd_disable.has("likely") or gccd_disable.has("all") then
592 self.header.add_decl("#define likely(x) (x)")
593 self.header.add_decl("#define unlikely(x) (x)")
594 else if gccd_disable.has("correct-likely") then
595 # invert the `likely` definition
596 # Used by masochists to bench the worst case
597 self.header.add_decl("#define likely(x) __builtin_expect((x),0)")
598 self.header.add_decl("#define unlikely(x) __builtin_expect((x),1)")
599 else
600 self.header.add_decl("#define likely(x) __builtin_expect((x),1)")
601 self.header.add_decl("#define unlikely(x) __builtin_expect((x),0)")
602 end
603
604 # Global variable used by intern methods
605 self.header.add_decl("extern int glob_argc;")
606 self.header.add_decl("extern char **glob_argv;")
607 self.header.add_decl("extern val *glob_sys;")
608 end
609
610 # Declaration of structures for live Nit types
611 protected fun compile_header_structs is abstract
612
613 # Declaration of structures for nitni undelying the FFI
614 protected fun compile_nitni_structs
615 do
616 self.header.add_decl """
617 /* Native reference to Nit objects */
618 /* This structure is used to represent every Nit type in extern methods and custom C code. */
619 struct nitni_ref {
620 struct nitni_ref *next,
621 *prev; /* adjacent global references in global list */
622 int count; /* number of time this global reference has been marked */
623 };
624
625 /* List of global references from C code to Nit objects */
626 /* Instanciated empty at init of Nit system and filled explicitly by user in C code */
627 struct nitni_global_ref_list_t {
628 struct nitni_ref *head, *tail;
629 };
630 extern struct nitni_global_ref_list_t *nitni_global_ref_list;
631
632 /* Initializer of global reference list */
633 extern void nitni_global_ref_list_init();
634
635 /* Intern function to add a global reference to the list */
636 extern void nitni_global_ref_add( struct nitni_ref *ref );
637
638 /* Intern function to remove a global reference from the list */
639 extern void nitni_global_ref_remove( struct nitni_ref *ref );
640
641 /* Increase count on an existing global reference */
642 extern void nitni_global_ref_incr( struct nitni_ref *ref );
643
644 /* Decrease count on an existing global reference */
645 extern void nitni_global_ref_decr( struct nitni_ref *ref );
646 """
647 end
648
649 fun compile_finalizer_function
650 do
651 var finalizable_type = mainmodule.finalizable_type
652 if finalizable_type == null then return
653
654 var finalize_meth = mainmodule.try_get_primitive_method("finalize", finalizable_type.mclass)
655
656 if finalize_meth == null then
657 modelbuilder.toolcontext.error(null, "The `Finalizable` class doesn't declare the `finalize` method.")
658 return
659 end
660
661 var v = self.new_visitor
662 v.add_decl "void gc_finalize (void *obj, void *client_data) \{"
663 var recv = v.new_expr("obj", finalizable_type)
664 v.send(finalize_meth, [recv])
665 v.add "\}"
666 end
667
668 # Generate the main C function.
669 #
670 # This function:
671 #
672 # * allocate the Sys object if it exists
673 # * call init if is exists
674 # * call main if it exists
675 fun compile_main_function
676 do
677 var v = self.new_visitor
678 v.add_decl("#include <signal.h>")
679 var ost = modelbuilder.toolcontext.opt_stacktrace.value
680 var platform = mainmodule.target_platform
681
682 if platform != null and not platform.supports_libunwind then ost = "none"
683
684 var no_main = (platform != null and platform.no_main) or modelbuilder.toolcontext.opt_no_main.value
685
686 if ost == "nitstack" or ost == "libunwind" then
687 v.add_decl("#define UNW_LOCAL_ONLY")
688 v.add_decl("#include <libunwind.h>")
689 if ost == "nitstack" then
690 v.add_decl("#include \"c_functions_hash.h\"")
691 end
692 end
693 v.add_decl("int glob_argc;")
694 v.add_decl("char **glob_argv;")
695 v.add_decl("val *glob_sys;")
696
697 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
698 for tag in count_type_test_tags do
699 v.add_decl("long count_type_test_resolved_{tag};")
700 v.add_decl("long count_type_test_unresolved_{tag};")
701 v.add_decl("long count_type_test_skipped_{tag};")
702 v.compiler.header.add_decl("extern long count_type_test_resolved_{tag};")
703 v.compiler.header.add_decl("extern long count_type_test_unresolved_{tag};")
704 v.compiler.header.add_decl("extern long count_type_test_skipped_{tag};")
705 end
706 end
707
708 if self.modelbuilder.toolcontext.opt_invocation_metrics.value then
709 v.add_decl("long count_invoke_by_tables;")
710 v.add_decl("long count_invoke_by_direct;")
711 v.add_decl("long count_invoke_by_inline;")
712 v.compiler.header.add_decl("extern long count_invoke_by_tables;")
713 v.compiler.header.add_decl("extern long count_invoke_by_direct;")
714 v.compiler.header.add_decl("extern long count_invoke_by_inline;")
715 end
716
717 if self.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
718 v.add_decl("long count_attr_reads = 0;")
719 v.add_decl("long count_isset_checks = 0;")
720 v.compiler.header.add_decl("extern long count_attr_reads;")
721 v.compiler.header.add_decl("extern long count_isset_checks;")
722 end
723
724 v.add_decl("void sig_handler(int signo)\{")
725 v.add_decl("PRINT_ERROR(\"Caught signal : %s\\n\", strsignal(signo));")
726 v.add_decl("show_backtrace(signo);")
727 v.add_decl("\}")
728
729 v.add_decl("void show_backtrace (int signo) \{")
730 if ost == "nitstack" or ost == "libunwind" then
731 v.add_decl("char* opt = getenv(\"NIT_NO_STACK\");")
732 v.add_decl("unw_cursor_t cursor;")
733 v.add_decl("if(opt==NULL)\{")
734 v.add_decl("unw_context_t uc;")
735 v.add_decl("unw_word_t ip;")
736 v.add_decl("char* procname = malloc(sizeof(char) * 100);")
737 v.add_decl("unw_getcontext(&uc);")
738 v.add_decl("unw_init_local(&cursor, &uc);")
739 v.add_decl("PRINT_ERROR(\"-------------------------------------------------\\n\");")
740 v.add_decl("PRINT_ERROR(\"-- Stack Trace ------------------------------\\n\");")
741 v.add_decl("PRINT_ERROR(\"-------------------------------------------------\\n\");")
742 v.add_decl("while (unw_step(&cursor) > 0) \{")
743 v.add_decl(" unw_get_proc_name(&cursor, procname, 100, &ip);")
744 if ost == "nitstack" then
745 v.add_decl(" const char* recv = get_nit_name(procname, strlen(procname));")
746 v.add_decl(" if (recv != NULL)\{")
747 v.add_decl(" PRINT_ERROR(\"` %s\\n\", recv);")
748 v.add_decl(" \}else\{")
749 v.add_decl(" PRINT_ERROR(\"` %s\\n\", procname);")
750 v.add_decl(" \}")
751 else
752 v.add_decl(" PRINT_ERROR(\"` %s \\n\",procname);")
753 end
754 v.add_decl("\}")
755 v.add_decl("PRINT_ERROR(\"-------------------------------------------------\\n\");")
756 v.add_decl("free(procname);")
757 v.add_decl("\}")
758 end
759 v.add_decl("exit(signo);")
760 v.add_decl("\}")
761
762 if no_main then
763 v.add_decl("int nit_main(int argc, char** argv) \{")
764 else
765 v.add_decl("int main(int argc, char** argv) \{")
766 end
767
768 v.add("signal(SIGABRT, sig_handler);")
769 v.add("signal(SIGFPE, sig_handler);")
770 v.add("signal(SIGILL, sig_handler);")
771 v.add("signal(SIGINT, sig_handler);")
772 v.add("signal(SIGTERM, sig_handler);")
773 v.add("signal(SIGSEGV, sig_handler);")
774 v.add("signal(SIGPIPE, sig_handler);")
775
776 v.add("glob_argc = argc; glob_argv = argv;")
777 v.add("initialize_gc_option();")
778
779 v.add "initialize_nitni_global_refs();"
780
781 var main_type = mainmodule.sys_type
782 if main_type != null then
783 var mainmodule = v.compiler.mainmodule
784 var glob_sys = v.init_instance(main_type)
785 v.add("glob_sys = {glob_sys};")
786 var main_init = mainmodule.try_get_primitive_method("init", main_type.mclass)
787 if main_init != null then
788 v.send(main_init, [glob_sys])
789 end
790 var main_method = mainmodule.try_get_primitive_method("run", main_type.mclass) or else
791 mainmodule.try_get_primitive_method("main", main_type.mclass)
792 if main_method != null then
793 v.send(main_method, [glob_sys])
794 end
795 end
796
797 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
798 v.add_decl("long count_type_test_resolved_total = 0;")
799 v.add_decl("long count_type_test_unresolved_total = 0;")
800 v.add_decl("long count_type_test_skipped_total = 0;")
801 v.add_decl("long count_type_test_total_total = 0;")
802 for tag in count_type_test_tags do
803 v.add_decl("long count_type_test_total_{tag};")
804 v.add("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
805 v.add("count_type_test_resolved_total += count_type_test_resolved_{tag};")
806 v.add("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
807 v.add("count_type_test_skipped_total += count_type_test_skipped_{tag};")
808 v.add("count_type_test_total_total += count_type_test_total_{tag};")
809 end
810 v.add("printf(\"# dynamic count_type_test: total %l\\n\");")
811 v.add("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\");")
812 var tags = count_type_test_tags.to_a
813 tags.add("total")
814 for tag in tags do
815 v.add("printf(\"{tag}\");")
816 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
817 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
818 v.add("printf(\"\\t%ld (%.2f%%)\", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
819 v.add("printf(\"\\t%ld (%.2f%%)\\n\", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
820 end
821 end
822
823 if self.modelbuilder.toolcontext.opt_invocation_metrics.value then
824 v.add_decl("long count_invoke_total;")
825 v.add("count_invoke_total = count_invoke_by_tables + count_invoke_by_direct + count_invoke_by_inline;")
826 v.add("printf(\"# dynamic count_invocation: total %ld\\n\", count_invoke_total);")
827 v.add("printf(\"by table: %ld (%.2f%%)\\n\", count_invoke_by_tables, 100.0*count_invoke_by_tables/count_invoke_total);")
828 v.add("printf(\"direct: %ld (%.2f%%)\\n\", count_invoke_by_direct, 100.0*count_invoke_by_direct/count_invoke_total);")
829 v.add("printf(\"inlined: %ld (%.2f%%)\\n\", count_invoke_by_inline, 100.0*count_invoke_by_inline/count_invoke_total);")
830 end
831
832 if self.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
833 v.add("printf(\"# dynamic attribute reads: %ld\\n\", count_attr_reads);")
834 v.add("printf(\"# dynamic isset checks: %ld\\n\", count_isset_checks);")
835 end
836
837 v.add("return 0;")
838 v.add("\}")
839 end
840
841 # Copile all C functions related to the [incr|decr]_ref features of the FFI
842 fun compile_nitni_global_ref_functions
843 do
844 var v = self.new_visitor
845 v.add """
846 struct nitni_global_ref_list_t *nitni_global_ref_list;
847 void initialize_nitni_global_refs() {
848 nitni_global_ref_list = (struct nitni_global_ref_list_t*)nit_alloc(sizeof(struct nitni_global_ref_list_t));
849 nitni_global_ref_list->head = NULL;
850 nitni_global_ref_list->tail = NULL;
851 }
852
853 void nitni_global_ref_add( struct nitni_ref *ref ) {
854 if ( nitni_global_ref_list->head == NULL ) {
855 nitni_global_ref_list->head = ref;
856 ref->prev = NULL;
857 } else {
858 nitni_global_ref_list->tail->next = ref;
859 ref->prev = nitni_global_ref_list->tail;
860 }
861 nitni_global_ref_list->tail = ref;
862
863 ref->next = NULL;
864 }
865
866 void nitni_global_ref_remove( struct nitni_ref *ref ) {
867 if ( ref->prev == NULL ) {
868 nitni_global_ref_list->head = ref->next;
869 } else {
870 ref->prev->next = ref->next;
871 }
872
873 if ( ref->next == NULL ) {
874 nitni_global_ref_list->tail = ref->prev;
875 } else {
876 ref->next->prev = ref->prev;
877 }
878 }
879
880 extern void nitni_global_ref_incr( struct nitni_ref *ref ) {
881 if ( ref->count == 0 ) /* not registered */
882 {
883 /* add to list */
884 nitni_global_ref_add( ref );
885 }
886
887 ref->count ++;
888 }
889
890 extern void nitni_global_ref_decr( struct nitni_ref *ref ) {
891 if ( ref->count == 1 ) /* was last reference */
892 {
893 /* remove from list */
894 nitni_global_ref_remove( ref );
895 }
896
897 ref->count --;
898 }
899 """
900 end
901
902 # List of additional files required to compile (FFI)
903 var extern_bodies = new Array[ExternFile]
904
905 # List of source files to copy over to the compile dir
906 var files_to_copy = new Array[String]
907
908 # This is used to avoid adding an extern file more than once
909 private var seen_extern = new ArraySet[String]
910
911 # Generate code that initialize the attributes on a new instance
912 fun generate_init_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
913 do
914 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
915 self.mainmodule.linearize_mclassdefs(cds)
916 for cd in cds do
917 for npropdef in modelbuilder.collect_attr_propdef(cd) do
918 npropdef.init_expr(v, recv)
919 end
920 end
921 end
922
923 # Generate code that check if an attribute is correctly initialized
924 fun generate_check_attr(v: VISITOR, recv: RuntimeVariable, mtype: MClassType)
925 do
926 var cds = mtype.collect_mclassdefs(self.mainmodule).to_a
927 self.mainmodule.linearize_mclassdefs(cds)
928 for cd in cds do
929 for npropdef in modelbuilder.collect_attr_propdef(cd) do
930 npropdef.check_expr(v, recv)
931 end
932 end
933 end
934
935 # stats
936
937 var count_type_test_tags: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
938 var count_type_test_resolved: HashMap[String, Int] = init_count_type_test_tags
939 var count_type_test_unresolved: HashMap[String, Int] = init_count_type_test_tags
940 var count_type_test_skipped: HashMap[String, Int] = init_count_type_test_tags
941
942 protected fun init_count_type_test_tags: HashMap[String, Int]
943 do
944 var res = new HashMap[String, Int]
945 for tag in count_type_test_tags do
946 res[tag] = 0
947 end
948 return res
949 end
950
951 # Display stats about compilation process
952 #
953 # Metrics used:
954 #
955 # * type tests against resolved types (`x isa Collection[Animal]`)
956 # * type tests against unresolved types (`x isa Collection[E]`)
957 # * type tests skipped
958 # * type tests total
959 fun display_stats
960 do
961 if self.modelbuilder.toolcontext.opt_typing_test_metrics.value then
962 print "# static count_type_test"
963 print "\tresolved:\tunresolved\tskipped\ttotal"
964 var count_type_test_total = init_count_type_test_tags
965 count_type_test_resolved["total"] = 0
966 count_type_test_unresolved["total"] = 0
967 count_type_test_skipped["total"] = 0
968 count_type_test_total["total"] = 0
969 for tag in count_type_test_tags do
970 count_type_test_total[tag] = count_type_test_resolved[tag] + count_type_test_unresolved[tag] + count_type_test_skipped[tag]
971 count_type_test_resolved["total"] += count_type_test_resolved[tag]
972 count_type_test_unresolved["total"] += count_type_test_unresolved[tag]
973 count_type_test_skipped["total"] += count_type_test_skipped[tag]
974 count_type_test_total["total"] += count_type_test_total[tag]
975 end
976 var count_type_test = count_type_test_total["total"]
977 var tags = count_type_test_tags.to_a
978 tags.add("total")
979 for tag in tags do
980 printn tag
981 printn "\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
982 printn "\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
983 printn "\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
984 printn "\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
985 print ""
986 end
987 end
988 end
989
990 fun finalize_ffi_for_module(mmodule: MModule) do mmodule.finalize_ffi(self)
991
992 # Division facility
993 # Avoid division by zero by returning the string "n/a"
994 fun div(a,b:Int):String
995 do
996 if b == 0 then return "n/a"
997 return ((a*10000/b).to_f / 100.0).to_precision(2)
998 end
999 end
1000
1001 # A file unit (may be more than one file if
1002 # A file unit aim to be autonomous and is made or one or more `CodeWriter`s
1003 class CodeFile
1004 var name: String
1005 var writers = new Array[CodeWriter]
1006 var required_declarations = new HashSet[String]
1007 end
1008
1009 # Where to store generated lines
1010 class CodeWriter
1011 var file: CodeFile
1012 var lines: List[String] = new List[String]
1013 var decl_lines: List[String] = new List[String]
1014
1015 # Add a line in the main part of the generated C
1016 fun add(s: String) do self.lines.add(s)
1017
1018 # Add a line in the
1019 # (used for local or global declaration)
1020 fun add_decl(s: String) do self.decl_lines.add(s)
1021
1022 init
1023 do
1024 file.writers.add(self)
1025 end
1026 end
1027
1028 # A visitor on the AST of property definition that generate the C code.
1029 abstract class AbstractCompilerVisitor
1030
1031 type COMPILER: AbstractCompiler
1032
1033 # The associated compiler
1034 var compiler: COMPILER
1035
1036 # The current visited AST node
1037 var current_node: nullable ANode = null is writable
1038
1039 # The current `Frame`
1040 var frame: nullable Frame = null is writable
1041
1042 # Alias for self.compiler.mainmodule.object_type
1043 fun object_type: MClassType do return self.compiler.mainmodule.object_type
1044
1045 # Alias for self.compiler.mainmodule.bool_type
1046 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
1047
1048 var writer: CodeWriter is noinit
1049
1050 init
1051 do
1052 self.writer = new CodeWriter(compiler.files.last)
1053 end
1054
1055 # Force to get the primitive class named `name` or abort
1056 fun get_class(name: String): MClass do return self.compiler.mainmodule.get_primitive_class(name)
1057
1058 # Force to get the primitive property named `name` in the instance `recv` or abort
1059 fun get_property(name: String, recv: MType): MMethod
1060 do
1061 assert recv isa MClassType
1062 return self.compiler.modelbuilder.force_get_primitive_method(self.current_node, name, recv.mclass, self.compiler.mainmodule)
1063 end
1064
1065 fun compile_callsite(callsite: CallSite, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1066 do
1067 var initializers = callsite.mpropdef.initializers
1068 if not initializers.is_empty then
1069 var recv = arguments.first
1070
1071 var i = 1
1072 for p in initializers do
1073 if p isa MMethod then
1074 var args = [recv]
1075 for x in p.intro.msignature.mparameters do
1076 args.add arguments[i]
1077 i += 1
1078 end
1079 self.send(p, args)
1080 else if p isa MAttribute then
1081 self.write_attribute(p, recv, arguments[i])
1082 i += 1
1083 else abort
1084 end
1085 assert i == arguments.length
1086
1087 return self.send(callsite.mproperty, [recv])
1088 end
1089
1090 return self.send(callsite.mproperty, arguments)
1091 end
1092
1093 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable is abstract
1094
1095 fun calloc_array(ret_type: MType, arguments: Array[RuntimeVariable]) is abstract
1096
1097 fun native_array_def(pname: String, ret_type: nullable MType, arguments: Array[RuntimeVariable]) is abstract
1098
1099 # Evaluate `args` as expressions in the call of `mpropdef` on `recv`.
1100 # This method is used to manage varargs in signatures and returns the real array
1101 # of runtime variables to use in the call.
1102 fun varargize(mpropdef: MMethodDef, recv: RuntimeVariable, args: SequenceRead[AExpr]): Array[RuntimeVariable]
1103 do
1104 var msignature = mpropdef.new_msignature or else mpropdef.msignature.as(not null)
1105 var res = new Array[RuntimeVariable]
1106 res.add(recv)
1107
1108 if args.is_empty then return res
1109
1110 var vararg_rank = msignature.vararg_rank
1111 var vararg_len = args.length - msignature.arity
1112 if vararg_len < 0 then vararg_len = 0
1113
1114 for i in [0..msignature.arity[ do
1115 if i == vararg_rank then
1116 var ne = args[i]
1117 if ne isa AVarargExpr then
1118 var e = self.expr(ne.n_expr, null)
1119 res.add(e)
1120 continue
1121 end
1122 var vararg = new Array[RuntimeVariable]
1123 for j in [vararg_rank..vararg_rank+vararg_len] do
1124 var e = self.expr(args[j], null)
1125 vararg.add(e)
1126 end
1127 var elttype = msignature.mparameters[vararg_rank].mtype
1128 var arg = self.vararg_instance(mpropdef, recv, vararg, elttype)
1129 res.add(arg)
1130 else
1131 var j = i
1132 if i > vararg_rank then j += vararg_len
1133 var e = self.expr(args[j], null)
1134 res.add(e)
1135 end
1136 end
1137 return res
1138 end
1139
1140 # Type handling
1141
1142 # Anchor a type to the main module and the current receiver
1143 fun anchor(mtype: MType): MType
1144 do
1145 if not mtype.need_anchor then return mtype
1146 return mtype.anchor_to(self.compiler.mainmodule, self.frame.receiver)
1147 end
1148
1149 fun resolve_for(mtype: MType, recv: RuntimeVariable): MType
1150 do
1151 if not mtype.need_anchor then return mtype
1152 return mtype.resolve_for(recv.mcasttype, self.frame.receiver, self.compiler.mainmodule, true)
1153 end
1154
1155 # Unsafely cast a value to a new type
1156 # ie the result share the same C variable but my have a different mcasttype
1157 # NOTE: if the adaptation is useless then `value` is returned as it.
1158 # ENSURE: `result.name == value.name`
1159 fun autoadapt(value: RuntimeVariable, mtype: MType): RuntimeVariable
1160 do
1161 mtype = self.anchor(mtype)
1162 var valmtype = value.mcasttype
1163 if valmtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1164 return value
1165 end
1166
1167 if valmtype isa MNullableType and valmtype.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
1168 var res = new RuntimeVariable(value.name, valmtype, valmtype.mtype)
1169 return res
1170 else
1171 var res = new RuntimeVariable(value.name, valmtype, mtype)
1172 return res
1173 end
1174 end
1175
1176 # Generate a super call from a method definition
1177 fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1178
1179 # Adapt the arguments of a method according to targetted `MMethodDef`
1180 fun adapt_signature(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1181
1182 # Unbox all the arguments of a method when implemented `extern` or `intern`
1183 fun unbox_signature_extern(m: MMethodDef, args: Array[RuntimeVariable]) is abstract
1184
1185 # Box or unbox a value to another type iff a C type conversion is needed
1186 # ENSURE: `result.mtype.ctype == mtype.ctype`
1187 fun autobox(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1188
1189 # Box extern classes to be used in the generated code
1190 fun box_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1191
1192 # Unbox extern classes to be used in extern code (legacy NI and FFI)
1193 fun unbox_extern(value: RuntimeVariable, mtype: MType): RuntimeVariable is abstract
1194
1195 # Generate a polymorphic subtype test
1196 fun type_test(value: RuntimeVariable, mtype: MType, tag: String): RuntimeVariable is abstract
1197
1198 # Generate the code required to dynamically check if 2 objects share the same runtime type
1199 fun is_same_type_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1200
1201 # Generate a Nit "is" for two runtime_variables
1202 fun equal_test(value1, value2: RuntimeVariable): RuntimeVariable is abstract
1203
1204 # Sends
1205
1206 # Generate a static call on a method definition
1207 fun call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1208
1209 # Generate a polymorphic send for the method `m` and the arguments `args`
1210 fun send(m: MMethod, args: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1211
1212 # Generate a monomorphic send for the method `m`, the type `t` and the arguments `args`
1213 fun monomorphic_send(m: MMethod, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1214 do
1215 assert t isa MClassType
1216 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
1217 return self.call(propdef, t, args)
1218 end
1219
1220 # Generate a monomorphic super send from the method `m`, the type `t` and the arguments `args`
1221 fun monomorphic_super_send(m: MMethodDef, t: MType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1222 do
1223 assert t isa MClassType
1224 m = m.lookup_next_definition(self.compiler.mainmodule, t)
1225 return self.call(m, t, args)
1226 end
1227
1228 # Attributes handling
1229
1230 # Generate a polymorphic attribute is_set test
1231 fun isset_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1232
1233 # Generate a polymorphic attribute read
1234 fun read_attribute(a: MAttribute, recv: RuntimeVariable): RuntimeVariable is abstract
1235
1236 # Generate a polymorphic attribute write
1237 fun write_attribute(a: MAttribute, recv: RuntimeVariable, value: RuntimeVariable) is abstract
1238
1239 # Checks
1240
1241 # Add a check and an abort for a null receiver if needed
1242 fun check_recv_notnull(recv: RuntimeVariable)
1243 do
1244 if self.compiler.modelbuilder.toolcontext.opt_no_check_null.value then return
1245
1246 var maybenull = recv.mcasttype isa MNullableType or recv.mcasttype isa MNullType
1247 if maybenull then
1248 self.add("if (unlikely({recv} == NULL)) \{")
1249 self.add_abort("Receiver is null")
1250 self.add("\}")
1251 end
1252 end
1253
1254 # Names handling
1255
1256 private var names = new HashSet[String]
1257 private var last: Int = 0
1258
1259 # Return a new name based on `s` and unique in the visitor
1260 fun get_name(s: String): String
1261 do
1262 if not self.names.has(s) then
1263 self.names.add(s)
1264 return s
1265 end
1266 var i = self.last + 1
1267 loop
1268 var s2 = s + i.to_s
1269 if not self.names.has(s2) then
1270 self.last = i
1271 self.names.add(s2)
1272 return s2
1273 end
1274 i = i + 1
1275 end
1276 end
1277
1278 # Return an unique and stable identifier associated with an escapemark
1279 fun escapemark_name(e: nullable EscapeMark): String
1280 do
1281 assert e != null
1282 if escapemark_names.has_key(e) then return escapemark_names[e]
1283 var name = e.name
1284 if name == null then name = "label"
1285 name = get_name(name)
1286 escapemark_names[e] = name
1287 return name
1288 end
1289
1290 # Insert a C label for associated with an escapemark
1291 fun add_escape_label(e: nullable EscapeMark)
1292 do
1293 if e == null then return
1294 if e.escapes.is_empty then return
1295 add("BREAK_{escapemark_name(e)}: (void)0;")
1296 end
1297
1298 private var escapemark_names = new HashMap[EscapeMark, String]
1299
1300 # Return a "const char*" variable associated to the classname of the dynamic type of an object
1301 # NOTE: we do not return a `RuntimeVariable` "NativeString" as the class may not exist in the module/program
1302 fun class_name_string(value: RuntimeVariable): String is abstract
1303
1304 # Variables handling
1305
1306 protected var variables = new HashMap[Variable, RuntimeVariable]
1307
1308 # Return the local runtime_variable associated to a Nit local variable
1309 fun variable(variable: Variable): RuntimeVariable
1310 do
1311 if self.variables.has_key(variable) then
1312 return self.variables[variable]
1313 else
1314 var name = self.get_name("var_{variable.name}")
1315 var mtype = variable.declared_type.as(not null)
1316 mtype = self.anchor(mtype)
1317 var res = new RuntimeVariable(name, mtype, mtype)
1318 self.add_decl("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
1319 self.variables[variable] = res
1320 return res
1321 end
1322 end
1323
1324 # Return a new uninitialized local runtime_variable
1325 fun new_var(mtype: MType): RuntimeVariable
1326 do
1327 mtype = self.anchor(mtype)
1328 var name = self.get_name("var")
1329 var res = new RuntimeVariable(name, mtype, mtype)
1330 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1331 return res
1332 end
1333
1334 # The difference with `new_var` is the C static type of the local variable
1335 fun new_var_extern(mtype: MType): RuntimeVariable
1336 do
1337 mtype = self.anchor(mtype)
1338 var name = self.get_name("var")
1339 var res = new RuntimeVariable(name, mtype, mtype)
1340 self.add_decl("{mtype.ctype_extern} {name} /* : {mtype} for extern */;")
1341 return res
1342 end
1343
1344 # Return a new uninitialized named runtime_variable
1345 fun new_named_var(mtype: MType, name: String): RuntimeVariable
1346 do
1347 mtype = self.anchor(mtype)
1348 var res = new RuntimeVariable(name, mtype, mtype)
1349 self.add_decl("{mtype.ctype} {name} /* : {mtype} */;")
1350 return res
1351 end
1352
1353 # Correctly assign a left and a right value
1354 # Boxing and unboxing is performed if required
1355 fun assign(left, right: RuntimeVariable)
1356 do
1357 right = self.autobox(right, left.mtype)
1358 self.add("{left} = {right};")
1359 end
1360
1361 # Generate instances
1362
1363 # Generate a alloc-instance + init-attributes
1364 fun init_instance(mtype: MClassType): RuntimeVariable is abstract
1365
1366 # Set a GC finalizer on `recv`, only if `recv` isa Finalizable
1367 fun set_finalizer(recv: RuntimeVariable)
1368 do
1369 var mtype = recv.mtype
1370 var finalizable_type = compiler.mainmodule.finalizable_type
1371 if finalizable_type != null and not mtype.need_anchor and
1372 mtype.is_subtype(compiler.mainmodule, null, finalizable_type) then
1373 add "gc_register_finalizer({recv});"
1374 end
1375 end
1376
1377 # Generate an integer value
1378 fun int_instance(value: Int): RuntimeVariable
1379 do
1380 var res = self.new_var(self.get_class("Int").mclass_type)
1381 self.add("{res} = {value};")
1382 return res
1383 end
1384
1385 # Generate an integer value
1386 fun bool_instance(value: Bool): RuntimeVariable
1387 do
1388 var res = self.new_var(self.get_class("Bool").mclass_type)
1389 if value then
1390 self.add("{res} = 1;")
1391 else
1392 self.add("{res} = 0;")
1393 end
1394 return res
1395 end
1396
1397 # Generate a string value
1398 fun string_instance(string: String): RuntimeVariable
1399 do
1400 var mtype = self.get_class("String").mclass_type
1401 var name = self.get_name("varonce")
1402 self.add_decl("static {mtype.ctype} {name};")
1403 var res = self.new_var(mtype)
1404 self.add("if ({name}) \{")
1405 self.add("{res} = {name};")
1406 self.add("\} else \{")
1407 var native_mtype = self.get_class("NativeString").mclass_type
1408 var nat = self.new_var(native_mtype)
1409 self.add("{nat} = \"{string.escape_to_c}\";")
1410 var length = self.int_instance(string.length)
1411 self.add("{res} = {self.send(self.get_property("to_s_with_length", native_mtype), [nat, length]).as(not null)};")
1412 self.add("{name} = {res};")
1413 self.add("\}")
1414 return res
1415 end
1416
1417 fun value_instance(object: Object): RuntimeVariable
1418 do
1419 if object isa Int then
1420 return int_instance(object)
1421 else if object isa Bool then
1422 return bool_instance(object)
1423 else if object isa String then
1424 return string_instance(object)
1425 else
1426 abort
1427 end
1428 end
1429
1430 # Generate an array value
1431 fun array_instance(array: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1432
1433 # Get an instance of a array for a vararg
1434 fun vararg_instance(mpropdef: MPropDef, recv: RuntimeVariable, varargs: Array[RuntimeVariable], elttype: MType): RuntimeVariable is abstract
1435
1436 # Code generation
1437
1438 # Add a line in the main part of the generated C
1439 fun add(s: String) do self.writer.lines.add(s)
1440
1441 # Add a line in the
1442 # (used for local or global declaration)
1443 fun add_decl(s: String) do self.writer.decl_lines.add(s)
1444
1445 # Request the presence of a global declaration
1446 fun require_declaration(key: String)
1447 do
1448 var reqs = self.writer.file.required_declarations
1449 if reqs.has(key) then return
1450 reqs.add(key)
1451 var node = current_node
1452 if node != null then compiler.requirers_of_declarations[key] = node
1453 end
1454
1455 # Add a declaration in the local-header
1456 # The declaration is ensured to be present once
1457 fun declare_once(s: String)
1458 do
1459 self.compiler.provide_declaration(s, s)
1460 self.require_declaration(s)
1461 end
1462
1463 # look for a needed .h and .c file for a given .nit source-file
1464 # FIXME: bad API, parameter should be a `MModule`, not its source-file
1465 fun add_extern(file: String)
1466 do
1467 file = file.strip_extension(".nit")
1468 var tryfile = file + ".nit.h"
1469 if tryfile.file_exists then
1470 self.declare_once("#include \"{tryfile.basename("")}\"")
1471 self.compiler.files_to_copy.add(tryfile)
1472 end
1473 tryfile = file + "_nit.h"
1474 if tryfile.file_exists then
1475 self.declare_once("#include \"{tryfile.basename("")}\"")
1476 self.compiler.files_to_copy.add(tryfile)
1477 end
1478
1479 if self.compiler.seen_extern.has(file) then return
1480 self.compiler.seen_extern.add(file)
1481 tryfile = file + ".nit.c"
1482 if not tryfile.file_exists then
1483 tryfile = file + "_nit.c"
1484 if not tryfile.file_exists then return
1485 end
1486 var f = new ExternCFile(tryfile.basename(""), "")
1487 self.compiler.extern_bodies.add(f)
1488 self.compiler.files_to_copy.add(tryfile)
1489 end
1490
1491 # Return a new local runtime_variable initialized with the C expression `cexpr`.
1492 fun new_expr(cexpr: String, mtype: MType): RuntimeVariable
1493 do
1494 var res = new_var(mtype)
1495 self.add("{res} = {cexpr};")
1496 return res
1497 end
1498
1499 # Generate generic abort
1500 # used by aborts, asserts, casts, etc.
1501 fun add_abort(message: String)
1502 do
1503 self.add("PRINT_ERROR(\"Runtime error: %s\", \"{message.escape_to_c}\");")
1504 add_raw_abort
1505 end
1506
1507 fun add_raw_abort
1508 do
1509 if self.current_node != null and self.current_node.location.file != null then
1510 self.add("PRINT_ERROR(\" (%s:%d)\\n\", \"{self.current_node.location.file.filename.escape_to_c}\", {current_node.location.line_start});")
1511 else
1512 self.add("PRINT_ERROR(\"\\n\");")
1513 end
1514 self.add("show_backtrace(1);")
1515 end
1516
1517 # Add a dynamic cast
1518 fun add_cast(value: RuntimeVariable, mtype: MType, tag: String)
1519 do
1520 var res = self.type_test(value, mtype, tag)
1521 self.add("if (unlikely(!{res})) \{")
1522 var cn = self.class_name_string(value)
1523 self.add("PRINT_ERROR(\"Runtime error: Cast failed. Expected `%s`, got `%s`\", \"{mtype.to_s.escape_to_c}\", {cn});")
1524 self.add_raw_abort
1525 self.add("\}")
1526 end
1527
1528 # Generate a return with the value `s`
1529 fun ret(s: RuntimeVariable)
1530 do
1531 self.assign(self.frame.returnvar.as(not null), s)
1532 self.add("goto {self.frame.returnlabel.as(not null)};")
1533 end
1534
1535 # Compile a statement (if any)
1536 fun stmt(nexpr: nullable AExpr)
1537 do
1538 if nexpr == null then return
1539 var old = self.current_node
1540 self.current_node = nexpr
1541 nexpr.stmt(self)
1542 self.current_node = old
1543 end
1544
1545 # Compile an expression an return its result
1546 # `mtype` is the expected return type, pass null if no specific type is expected.
1547 fun expr(nexpr: AExpr, mtype: nullable MType): RuntimeVariable
1548 do
1549 var old = self.current_node
1550 self.current_node = nexpr
1551 var res = nexpr.expr(self).as(not null)
1552 if mtype != null then
1553 mtype = self.anchor(mtype)
1554 res = self.autobox(res, mtype)
1555 end
1556 res = autoadapt(res, nexpr.mtype.as(not null))
1557 var implicit_cast_to = nexpr.implicit_cast_to
1558 if implicit_cast_to != null and not self.compiler.modelbuilder.toolcontext.opt_no_check_autocast.value then
1559 add_cast(res, implicit_cast_to, "auto")
1560 res = autoadapt(res, implicit_cast_to)
1561 end
1562 self.current_node = old
1563 return res
1564 end
1565
1566 # Alias for `self.expr(nexpr, self.bool_type)`
1567 fun expr_bool(nexpr: AExpr): RuntimeVariable do return expr(nexpr, bool_type)
1568
1569 # Safely show a debug message on the current node and repeat the message in the C code as a comment
1570 fun debug(message: String)
1571 do
1572 var node = self.current_node
1573 if node == null then
1574 print "?: {message}"
1575 else
1576 node.debug(message)
1577 end
1578 self.add("/* DEBUG: {message} */")
1579 end
1580 end
1581
1582 # A C function associated to a Nit method
1583 # Because of customization, a given Nit method can be compiler more that once
1584 abstract class AbstractRuntimeFunction
1585
1586 type COMPILER: AbstractCompiler
1587 type VISITOR: AbstractCompilerVisitor
1588
1589 # The associated Nit method
1590 var mmethoddef: MMethodDef
1591
1592 # The mangled c name of the runtime_function
1593 # Subclasses should redefine `build_c_name` instead
1594 fun c_name: String
1595 do
1596 var res = self.c_name_cache
1597 if res != null then return res
1598 res = self.build_c_name
1599 self.c_name_cache = res
1600 return res
1601 end
1602
1603 # Non cached version of `c_name`
1604 protected fun build_c_name: String is abstract
1605
1606 protected var c_name_cache: nullable String = null is writable
1607
1608 # Implements a call of the runtime_function
1609 # May inline the body or generate a C function call
1610 fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
1611
1612 # Generate the code for the `AbstractRuntimeFunction`
1613 # Warning: compile more than once compilation makes CC unhappy
1614 fun compile_to_c(compiler: COMPILER) is abstract
1615 end
1616
1617 # A runtime variable hold a runtime value in C.
1618 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
1619 #
1620 # 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.
1621 class RuntimeVariable
1622 # The name of the variable in the C code
1623 var name: String
1624
1625 # The static type of the variable (as declard in C)
1626 var mtype: MType
1627
1628 # The current casted type of the variable (as known in Nit)
1629 var mcasttype: MType is writable
1630
1631 # If the variable exaclty a mcasttype?
1632 # false (usual value) means that the variable is a mcasttype or a subtype.
1633 var is_exact: Bool = false is writable
1634
1635 init
1636 do
1637 assert not mtype.need_anchor
1638 assert not mcasttype.need_anchor
1639 end
1640
1641 redef fun to_s do return name
1642
1643 redef fun inspect
1644 do
1645 var exact_str
1646 if self.is_exact then
1647 exact_str = " exact"
1648 else
1649 exact_str = ""
1650 end
1651 var type_str
1652 if self.mtype == self.mcasttype then
1653 type_str = "{mtype}{exact_str}"
1654 else
1655 type_str = "{mtype}({mcasttype}{exact_str})"
1656 end
1657 return "<{name}:{type_str}>"
1658 end
1659 end
1660
1661 # A frame correspond to a visited property in a `GlobalCompilerVisitor`
1662 class Frame
1663
1664 type VISITOR: AbstractCompilerVisitor
1665
1666 # The associated visitor
1667 var visitor: VISITOR
1668
1669 # The executed property.
1670 # A Method in case of a call, an attribute in case of a default initialization.
1671 var mpropdef: MPropDef
1672
1673 # The static type of the receiver
1674 var receiver: MClassType
1675
1676 # Arguments of the method (the first is the receiver)
1677 var arguments: Array[RuntimeVariable]
1678
1679 # The runtime_variable associated to the return (in a function)
1680 var returnvar: nullable RuntimeVariable = null is writable
1681
1682 # The label at the end of the property
1683 var returnlabel: nullable String = null is writable
1684 end
1685
1686 redef class MType
1687 # Return the C type associated to a given Nit static type
1688 fun ctype: String do return "val*"
1689
1690 # C type outside of the compiler code and in boxes
1691 fun ctype_extern: String do return "val*"
1692
1693 # Short name of the `ctype` to use in unions
1694 fun ctypename: String do return "val"
1695 end
1696
1697 redef class MClassType
1698
1699 redef fun ctype: String
1700 do
1701 if mclass.name == "Int" then
1702 return "long"
1703 else if mclass.name == "Bool" then
1704 return "short int"
1705 else if mclass.name == "Char" then
1706 return "char"
1707 else if mclass.name == "Float" then
1708 return "double"
1709 else if mclass.name == "NativeString" then
1710 return "char*"
1711 else if mclass.name == "NativeArray" then
1712 return "val*"
1713 else
1714 return "val*"
1715 end
1716 end
1717
1718 redef fun ctype_extern: String
1719 do
1720 if mclass.kind == extern_kind then
1721 return "void*"
1722 else
1723 return ctype
1724 end
1725 end
1726
1727 redef fun ctypename: String
1728 do
1729 if mclass.name == "Int" then
1730 return "l"
1731 else if mclass.name == "Bool" then
1732 return "s"
1733 else if mclass.name == "Char" then
1734 return "c"
1735 else if mclass.name == "Float" then
1736 return "d"
1737 else if mclass.name == "NativeString" then
1738 return "str"
1739 else if mclass.name == "NativeArray" then
1740 #return "{self.arguments.first.ctype}*"
1741 return "val"
1742 else
1743 return "val"
1744 end
1745 end
1746 end
1747
1748 redef class MPropDef
1749 type VISITOR: AbstractCompilerVisitor
1750 end
1751
1752 redef class MMethodDef
1753 # Can the body be inlined?
1754 fun can_inline(v: VISITOR): Bool
1755 do
1756 if is_abstract then return true
1757 var modelbuilder = v.compiler.modelbuilder
1758 var node = modelbuilder.mpropdef2node(self)
1759 if node isa APropdef then
1760 return node.can_inline
1761 else if node isa AClassdef then
1762 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1763 return true
1764 else
1765 abort
1766 end
1767 end
1768
1769 # Inline the body in another visitor
1770 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1771 do
1772 var modelbuilder = v.compiler.modelbuilder
1773 var val = constant_value
1774 var node = modelbuilder.mpropdef2node(self)
1775 if node isa APropdef then
1776 var oldnode = v.current_node
1777 v.current_node = node
1778 self.compile_parameter_check(v, arguments)
1779 node.compile_to_c(v, self, arguments)
1780 v.current_node = oldnode
1781 else if node isa AClassdef then
1782 var oldnode = v.current_node
1783 v.current_node = node
1784 self.compile_parameter_check(v, arguments)
1785 node.compile_to_c(v, self, arguments)
1786 v.current_node = oldnode
1787 else if val != null then
1788 v.ret(v.value_instance(val))
1789 else
1790 abort
1791 end
1792 return null
1793 end
1794
1795 # Generate type checks in the C code to check covariant parameters
1796 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1797 do
1798 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1799
1800 for i in [0..msignature.arity[ do
1801 # skip test for vararg since the array is instantiated with the correct polymorphic type
1802 if msignature.vararg_rank == i then continue
1803
1804 # skip if the cast is not required
1805 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1806 if not origmtype.need_anchor then continue
1807
1808 # get the parameter type
1809 var mtype = self.msignature.mparameters[i].mtype
1810
1811 # generate the cast
1812 # note that v decides if and how to implements the cast
1813 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1814 v.add_cast(arguments[i+1], mtype, "covariance")
1815 end
1816 end
1817 end
1818
1819 # Node visit
1820
1821 redef class APropdef
1822 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1823 do
1824 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1825 debug("Not yet implemented")
1826 end
1827
1828 fun can_inline: Bool do return true
1829 end
1830
1831 redef class AMethPropdef
1832 redef fun compile_to_c(v, mpropdef, arguments)
1833 do
1834 if mpropdef.is_abstract then
1835 var cn = v.class_name_string(arguments.first)
1836 v.add("PRINT_ERROR(\"Runtime error: Abstract method `%s` called on `%s`\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1837 v.add_raw_abort
1838 return
1839 end
1840
1841 # Call the implicit super-init
1842 var auto_super_inits = self.auto_super_inits
1843 if auto_super_inits != null then
1844 var args = [arguments.first]
1845 for auto_super_init in auto_super_inits do
1846 assert auto_super_init.mproperty != mpropdef.mproperty
1847 args.clear
1848 for i in [0..auto_super_init.msignature.arity+1[ do
1849 args.add(arguments[i])
1850 end
1851 assert auto_super_init.mproperty != mpropdef.mproperty
1852 v.compile_callsite(auto_super_init, args)
1853 end
1854 end
1855 if auto_super_call then
1856 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
1857 end
1858
1859 # Try special compilation
1860 if mpropdef.is_intern then
1861 if compile_intern_to_c(v, mpropdef, arguments) then return
1862 else if mpropdef.is_extern then
1863 if mpropdef.mproperty.is_init then
1864 if compile_externinit_to_c(v, mpropdef, arguments) then return
1865 else
1866 if compile_externmeth_to_c(v, mpropdef, arguments) then return
1867 end
1868 end
1869
1870 # Compile block if any
1871 var n_block = n_block
1872 if n_block != null then
1873 for i in [0..mpropdef.msignature.arity[ do
1874 var variable = self.n_signature.n_params[i].variable.as(not null)
1875 v.assign(v.variable(variable), arguments[i+1])
1876 end
1877 v.stmt(n_block)
1878 return
1879 end
1880
1881 # We have a problem
1882 var cn = v.class_name_string(arguments.first)
1883 v.add("PRINT_ERROR(\"Runtime error: uncompiled method `%s` called on `%s`. NOT YET IMPLEMENTED\", \"{mpropdef.mproperty.name.escape_to_c}\", {cn});")
1884 v.add_raw_abort
1885 end
1886
1887 redef fun can_inline
1888 do
1889 if self.auto_super_inits != null then return false
1890 var nblock = self.n_block
1891 if nblock == null then return true
1892 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1893 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1894 return false
1895 end
1896
1897 fun compile_intern_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
1898 do
1899 var pname = mpropdef.mproperty.name
1900 var cname = mpropdef.mclassdef.mclass.name
1901 var ret = mpropdef.msignature.return_mtype
1902 if ret != null then
1903 ret = v.resolve_for(ret, arguments.first)
1904 end
1905 if pname != "==" and pname != "!=" then
1906 v.adapt_signature(mpropdef, arguments)
1907 v.unbox_signature_extern(mpropdef, arguments)
1908 end
1909 if cname == "Int" then
1910 if pname == "output" then
1911 v.add("printf(\"%ld\\n\", {arguments.first});")
1912 return true
1913 else if pname == "object_id" then
1914 v.ret(arguments.first)
1915 return true
1916 else if pname == "+" then
1917 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1918 return true
1919 else if pname == "-" then
1920 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1921 return true
1922 else if pname == "unary -" then
1923 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1924 return true
1925 else if pname == "*" then
1926 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1927 return true
1928 else if pname == "/" then
1929 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1930 return true
1931 else if pname == "%" then
1932 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1933 return true
1934 else if pname == "lshift" then
1935 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1936 return true
1937 else if pname == "rshift" then
1938 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1939 return true
1940 else if pname == "==" then
1941 v.ret(v.equal_test(arguments[0], arguments[1]))
1942 return true
1943 else if pname == "!=" then
1944 var res = v.equal_test(arguments[0], arguments[1])
1945 v.ret(v.new_expr("!{res}", ret.as(not null)))
1946 return true
1947 else if pname == "<" then
1948 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1949 return true
1950 else if pname == ">" then
1951 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1952 return true
1953 else if pname == "<=" then
1954 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1955 return true
1956 else if pname == ">=" then
1957 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1958 return true
1959 else if pname == "to_f" then
1960 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
1961 return true
1962 else if pname == "ascii" then
1963 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1964 return true
1965 end
1966 else if cname == "Char" then
1967 if pname == "output" then
1968 v.add("printf(\"%c\", {arguments.first});")
1969 return true
1970 else if pname == "object_id" then
1971 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
1972 return true
1973 else if pname == "successor" then
1974 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1975 return true
1976 else if pname == "predecessor" then
1977 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1978 return true
1979 else if pname == "==" then
1980 v.ret(v.equal_test(arguments[0], arguments[1]))
1981 return true
1982 else if pname == "!=" then
1983 var res = v.equal_test(arguments[0], arguments[1])
1984 v.ret(v.new_expr("!{res}", ret.as(not null)))
1985 return true
1986 else if pname == "<" then
1987 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1988 return true
1989 else if pname == ">" then
1990 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1991 return true
1992 else if pname == "<=" then
1993 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1994 return true
1995 else if pname == ">=" then
1996 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1997 return true
1998 else if pname == "to_i" then
1999 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
2000 return true
2001 else if pname == "ascii" then
2002 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
2003 return true
2004 end
2005 else if cname == "Bool" then
2006 if pname == "output" then
2007 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
2008 return true
2009 else if pname == "object_id" then
2010 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2011 return true
2012 else if pname == "==" then
2013 v.ret(v.equal_test(arguments[0], arguments[1]))
2014 return true
2015 else if pname == "!=" then
2016 var res = v.equal_test(arguments[0], arguments[1])
2017 v.ret(v.new_expr("!{res}", ret.as(not null)))
2018 return true
2019 end
2020 else if cname == "Float" then
2021 if pname == "output" then
2022 v.add("printf(\"%f\\n\", {arguments.first});")
2023 return true
2024 else if pname == "object_id" then
2025 v.ret(v.new_expr("(double){arguments.first}", ret.as(not null)))
2026 return true
2027 else if pname == "+" then
2028 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
2029 return true
2030 else if pname == "-" then
2031 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
2032 return true
2033 else if pname == "unary -" then
2034 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
2035 return true
2036 else if pname == "succ" then
2037 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
2038 return true
2039 else if pname == "prec" then
2040 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
2041 return true
2042 else if pname == "*" then
2043 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
2044 return true
2045 else if pname == "/" then
2046 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
2047 return true
2048 else if pname == "==" then
2049 v.ret(v.equal_test(arguments[0], arguments[1]))
2050 return true
2051 else if pname == "!=" then
2052 var res = v.equal_test(arguments[0], arguments[1])
2053 v.ret(v.new_expr("!{res}", ret.as(not null)))
2054 return true
2055 else if pname == "<" then
2056 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
2057 return true
2058 else if pname == ">" then
2059 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
2060 return true
2061 else if pname == "<=" then
2062 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
2063 return true
2064 else if pname == ">=" then
2065 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
2066 return true
2067 else if pname == "to_i" then
2068 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
2069 return true
2070 end
2071 else if cname == "NativeString" then
2072 if pname == "[]" then
2073 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
2074 return true
2075 else if pname == "[]=" then
2076 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
2077 return true
2078 else if pname == "copy_to" then
2079 v.add("memmove({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
2080 return true
2081 else if pname == "atoi" then
2082 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
2083 return true
2084 else if pname == "new" then
2085 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2086 return true
2087 end
2088 else if cname == "NativeArray" then
2089 v.native_array_def(pname, ret, arguments)
2090 return true
2091 end
2092 if pname == "exit" then
2093 v.add("exit({arguments[1]});")
2094 return true
2095 else if pname == "sys" then
2096 v.ret(v.new_expr("glob_sys", ret.as(not null)))
2097 return true
2098 else if pname == "calloc_string" then
2099 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
2100 return true
2101 else if pname == "calloc_array" then
2102 v.calloc_array(ret.as(not null), arguments)
2103 return true
2104 else if pname == "object_id" then
2105 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
2106 return true
2107 else if pname == "is_same_type" then
2108 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
2109 return true
2110 else if pname == "is_same_instance" then
2111 v.ret(v.equal_test(arguments[0], arguments[1]))
2112 return true
2113 else if pname == "output_class_name" then
2114 var nat = v.class_name_string(arguments.first)
2115 v.add("printf(\"%s\\n\", {nat});")
2116 return true
2117 else if pname == "native_class_name" then
2118 var nat = v.class_name_string(arguments.first)
2119 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
2120 return true
2121 else if pname == "force_garbage_collection" then
2122 v.add("nit_gcollect();")
2123 return true
2124 else if pname == "native_argc" then
2125 v.ret(v.new_expr("glob_argc", ret.as(not null)))
2126 return true
2127 else if pname == "native_argv" then
2128 v.ret(v.new_expr("glob_argv[{arguments[1]}]", ret.as(not null)))
2129 return true
2130 end
2131 return false
2132 end
2133
2134 # Compile an extern method
2135 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2136 fun compile_externmeth_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
2137 do
2138 var externname
2139 var at = self.get_single_annotation("extern", v.compiler.modelbuilder)
2140 if at != null then
2141 externname = at.arg_as_string(v.compiler.modelbuilder)
2142 if externname == null then return false
2143 else
2144 return false
2145 end
2146 if location.file != null then
2147 var file = location.file.filename
2148 v.add_extern(file)
2149 end
2150 var res: nullable RuntimeVariable = null
2151 var ret = mpropdef.msignature.return_mtype
2152 if ret != null then
2153 ret = v.resolve_for(ret, arguments.first)
2154 res = v.new_var_extern(ret)
2155 end
2156 v.adapt_signature(mpropdef, arguments)
2157 v.unbox_signature_extern(mpropdef, arguments)
2158
2159 if res == null then
2160 v.add("{externname}({arguments.join(", ")});")
2161 else
2162 v.add("{res} = {externname}({arguments.join(", ")});")
2163 res = v.box_extern(res, ret.as(not null))
2164 v.ret(res)
2165 end
2166 return true
2167 end
2168
2169 # Compile an extern factory
2170 # Return `true` if the compilation was successful, `false` if a fall-back is needed
2171 fun compile_externinit_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable]): Bool
2172 do
2173 var externname
2174 var at = self.get_single_annotation("extern", v.compiler.modelbuilder)
2175 if at != null then
2176 externname = at.arg_as_string(v.compiler.modelbuilder)
2177 if externname == null then return false
2178 else
2179 return false
2180 end
2181 if location.file != null then
2182 var file = location.file.filename
2183 v.add_extern(file)
2184 end
2185 v.adapt_signature(mpropdef, arguments)
2186 v.unbox_signature_extern(mpropdef, arguments)
2187 var ret = arguments.first.mtype
2188 var res = v.new_var_extern(ret)
2189
2190 arguments.shift
2191
2192 v.add("{res} = {externname}({arguments.join(", ")});")
2193 res = v.box_extern(res, ret)
2194 v.ret(res)
2195 return true
2196 end
2197 end
2198
2199 redef class AAttrPropdef
2200 redef fun compile_to_c(v, mpropdef, arguments)
2201 do
2202 if mpropdef == mreadpropdef then
2203 assert arguments.length == 1
2204 var recv = arguments.first
2205 var res
2206 if is_lazy then
2207 var set
2208 var ret = self.mpropdef.static_mtype
2209 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2210 var guard = self.mlazypropdef.mproperty
2211 if useiset then
2212 set = v.isset_attribute(self.mpropdef.mproperty, recv)
2213 else
2214 set = v.read_attribute(guard, recv)
2215 end
2216 v.add("if(likely({set})) \{")
2217 res = v.read_attribute(self.mpropdef.mproperty, recv)
2218 v.add("\} else \{")
2219
2220 var value = evaluate_expr(v, recv)
2221
2222 v.assign(res, value)
2223 if not useiset then
2224 var true_v = v.new_expr("1", v.bool_type)
2225 v.write_attribute(guard, arguments.first, true_v)
2226 end
2227 v.add("\}")
2228 else
2229 res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
2230 end
2231 v.assign(v.frame.returnvar.as(not null), res)
2232 else if mpropdef == mwritepropdef then
2233 assert arguments.length == 2
2234 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
2235 if is_lazy then
2236 var ret = self.mpropdef.static_mtype
2237 var useiset = ret.ctype == "val*" and not ret isa MNullableType
2238 if not useiset then
2239 v.write_attribute(self.mlazypropdef.mproperty, arguments.first, v.new_expr("1", v.bool_type))
2240 end
2241 end
2242 else
2243 abort
2244 end
2245 end
2246
2247 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2248 do
2249 if has_value and not is_lazy then evaluate_expr(v, recv)
2250 end
2251
2252 # Evaluate, store and return the default value of the attribute
2253 private fun evaluate_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable): RuntimeVariable
2254 do
2255 var oldnode = v.current_node
2256 v.current_node = self
2257 var old_frame = v.frame
2258 var frame = new Frame(v, self.mpropdef.as(not null), recv.mcasttype.as(MClassType), [recv])
2259 v.frame = frame
2260
2261 var value
2262 var mtype = self.mpropdef.static_mtype
2263 assert mtype != null
2264
2265 var nexpr = self.n_expr
2266 var nblock = self.n_block
2267 if nexpr != null then
2268 value = v.expr(nexpr, mtype)
2269 else if nblock != null then
2270 value = v.new_var(mtype)
2271 frame.returnvar = value
2272 frame.returnlabel = v.get_name("RET_LABEL")
2273 v.add("\{")
2274 v.stmt(nblock)
2275 v.add("{frame.returnlabel.as(not null)}:(void)0;")
2276 v.add("\}")
2277 else
2278 abort
2279 end
2280
2281 v.write_attribute(self.mpropdef.mproperty, recv, value)
2282
2283 v.frame = old_frame
2284 v.current_node = oldnode
2285
2286 return value
2287 end
2288
2289 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
2290 do
2291 var nexpr = self.n_expr
2292 if nexpr != null then return
2293
2294 var oldnode = v.current_node
2295 v.current_node = self
2296 var old_frame = v.frame
2297 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
2298 v.frame = frame
2299 # Force read to check the initialization
2300 v.read_attribute(self.mpropdef.mproperty, recv)
2301 v.frame = old_frame
2302 v.current_node = oldnode
2303 end
2304 end
2305
2306 redef class AClassdef
2307 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
2308 do
2309 if mpropdef == self.mfree_init then
2310 assert mpropdef.mproperty.is_root_init
2311 assert arguments.length == 1
2312 if not mpropdef.is_intro then
2313 v.supercall(mpropdef, arguments.first.mtype.as(MClassType), arguments)
2314 end
2315 return
2316 else
2317 abort
2318 end
2319 end
2320 end
2321
2322 redef class AExpr
2323 # Try to compile self as an expression
2324 # Do not call this method directly, use `v.expr` instead
2325 private fun expr(v: AbstractCompilerVisitor): nullable RuntimeVariable
2326 do
2327 v.add("PRINT_ERROR(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\");")
2328 var mtype = self.mtype
2329 if mtype == null then
2330 return null
2331 else
2332 var res = v.new_var(mtype)
2333 v.add("/* {res} = NOT YET {class_name} */")
2334 return res
2335 end
2336 end
2337
2338 # Try to compile self as a statement
2339 # Do not call this method directly, use `v.stmt` instead
2340 private fun stmt(v: AbstractCompilerVisitor)
2341 do
2342 expr(v)
2343 end
2344 end
2345
2346 redef class ABlockExpr
2347 redef fun stmt(v)
2348 do
2349 for e in self.n_expr do v.stmt(e)
2350 end
2351 redef fun expr(v)
2352 do
2353 var last = self.n_expr.last
2354 for e in self.n_expr do
2355 if e == last then break
2356 v.stmt(e)
2357 end
2358 return v.expr(last, null)
2359 end
2360 end
2361
2362 redef class AVardeclExpr
2363 redef fun stmt(v)
2364 do
2365 var variable = self.variable.as(not null)
2366 var ne = self.n_expr
2367 if ne != null then
2368 var i = v.expr(ne, variable.declared_type)
2369 v.assign(v.variable(variable), i)
2370 end
2371 end
2372 end
2373
2374 redef class AVarExpr
2375 redef fun expr(v)
2376 do
2377 var res = v.variable(self.variable.as(not null))
2378 var mtype = self.mtype.as(not null)
2379 return v.autoadapt(res, mtype)
2380 end
2381 end
2382
2383 redef class AVarAssignExpr
2384 redef fun expr(v)
2385 do
2386 var variable = self.variable.as(not null)
2387 var i = v.expr(self.n_value, variable.declared_type)
2388 v.assign(v.variable(variable), i)
2389 return i
2390 end
2391 end
2392
2393 redef class AVarReassignExpr
2394 redef fun stmt(v)
2395 do
2396 var variable = self.variable.as(not null)
2397 var vari = v.variable(variable)
2398 var value = v.expr(self.n_value, variable.declared_type)
2399 var res = v.compile_callsite(self.reassign_callsite.as(not null), [vari, value])
2400 assert res != null
2401 v.assign(v.variable(variable), res)
2402 end
2403 end
2404
2405 redef class ASelfExpr
2406 redef fun expr(v) do return v.frame.arguments.first
2407 end
2408
2409 redef class AEscapeExpr
2410 redef fun stmt(v) do v.add("goto BREAK_{v.escapemark_name(self.escapemark)};")
2411 end
2412
2413 redef class AReturnExpr
2414 redef fun stmt(v)
2415 do
2416 var nexpr = self.n_expr
2417 if nexpr != null then
2418 var returnvar = v.frame.returnvar.as(not null)
2419 var i = v.expr(nexpr, returnvar.mtype)
2420 v.assign(returnvar, i)
2421 end
2422 v.add("goto {v.frame.returnlabel.as(not null)};")
2423 end
2424 end
2425
2426 redef class AAbortExpr
2427 redef fun stmt(v) do v.add_abort("Aborted")
2428 end
2429
2430 redef class AIfExpr
2431 redef fun stmt(v)
2432 do
2433 var cond = v.expr_bool(self.n_expr)
2434 v.add("if ({cond})\{")
2435 v.stmt(self.n_then)
2436 v.add("\} else \{")
2437 v.stmt(self.n_else)
2438 v.add("\}")
2439 end
2440
2441 redef fun expr(v)
2442 do
2443 var res = v.new_var(self.mtype.as(not null))
2444 var cond = v.expr_bool(self.n_expr)
2445 v.add("if ({cond})\{")
2446 v.assign(res, v.expr(self.n_then.as(not null), null))
2447 v.add("\} else \{")
2448 v.assign(res, v.expr(self.n_else.as(not null), null))
2449 v.add("\}")
2450 return res
2451 end
2452 end
2453
2454 redef class AIfexprExpr
2455 redef fun expr(v)
2456 do
2457 var res = v.new_var(self.mtype.as(not null))
2458 var cond = v.expr_bool(self.n_expr)
2459 v.add("if ({cond})\{")
2460 v.assign(res, v.expr(self.n_then, null))
2461 v.add("\} else \{")
2462 v.assign(res, v.expr(self.n_else, null))
2463 v.add("\}")
2464 return res
2465 end
2466 end
2467
2468 redef class ADoExpr
2469 redef fun stmt(v)
2470 do
2471 v.stmt(self.n_block)
2472 v.add_escape_label(break_mark)
2473 end
2474 end
2475
2476 redef class AWhileExpr
2477 redef fun stmt(v)
2478 do
2479 v.add("for(;;) \{")
2480 var cond = v.expr_bool(self.n_expr)
2481 v.add("if (!{cond}) break;")
2482 v.stmt(self.n_block)
2483 v.add_escape_label(continue_mark)
2484 v.add("\}")
2485 v.add_escape_label(break_mark)
2486 end
2487 end
2488
2489 redef class ALoopExpr
2490 redef fun stmt(v)
2491 do
2492 v.add("for(;;) \{")
2493 v.stmt(self.n_block)
2494 v.add_escape_label(continue_mark)
2495 v.add("\}")
2496 v.add_escape_label(break_mark)
2497 end
2498 end
2499
2500 redef class AForExpr
2501 redef fun stmt(v)
2502 do
2503 var cl = v.expr(self.n_expr, null)
2504 var it_meth = self.method_iterator
2505 assert it_meth != null
2506 var it = v.compile_callsite(it_meth, [cl])
2507 assert it != null
2508 v.add("for(;;) \{")
2509 var isok_meth = self.method_is_ok
2510 assert isok_meth != null
2511 var ok = v.compile_callsite(isok_meth, [it])
2512 assert ok != null
2513 v.add("if(!{ok}) break;")
2514 if self.variables.length == 1 then
2515 var item_meth = self.method_item
2516 assert item_meth != null
2517 var i = v.compile_callsite(item_meth, [it])
2518 assert i != null
2519 v.assign(v.variable(variables.first), i)
2520 else if self.variables.length == 2 then
2521 var key_meth = self.method_key
2522 assert key_meth != null
2523 var i = v.compile_callsite(key_meth, [it])
2524 assert i != null
2525 v.assign(v.variable(variables[0]), i)
2526 var item_meth = self.method_item
2527 assert item_meth != null
2528 i = v.compile_callsite(item_meth, [it])
2529 assert i != null
2530 v.assign(v.variable(variables[1]), i)
2531 else
2532 abort
2533 end
2534 v.stmt(self.n_block)
2535 v.add_escape_label(continue_mark)
2536 var next_meth = self.method_next
2537 assert next_meth != null
2538 v.compile_callsite(next_meth, [it])
2539 v.add("\}")
2540 v.add_escape_label(break_mark)
2541
2542 var method_finish = self.method_finish
2543 if method_finish != null then
2544 # TODO: Find a way to call this also in long escape (e.g. return)
2545 v.compile_callsite(method_finish, [it])
2546 end
2547 end
2548 end
2549
2550 redef class AAssertExpr
2551 redef fun stmt(v)
2552 do
2553 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return
2554
2555 var cond = v.expr_bool(self.n_expr)
2556 v.add("if (unlikely(!{cond})) \{")
2557 v.stmt(self.n_else)
2558 var nid = self.n_id
2559 if nid != null then
2560 v.add_abort("Assert '{nid.text}' failed")
2561 else
2562 v.add_abort("Assert failed")
2563 end
2564 v.add("\}")
2565 end
2566 end
2567
2568 redef class AOrExpr
2569 redef fun expr(v)
2570 do
2571 var res = v.new_var(self.mtype.as(not null))
2572 var i1 = v.expr_bool(self.n_expr)
2573 v.add("if ({i1}) \{")
2574 v.add("{res} = 1;")
2575 v.add("\} else \{")
2576 var i2 = v.expr_bool(self.n_expr2)
2577 v.add("{res} = {i2};")
2578 v.add("\}")
2579 return res
2580 end
2581 end
2582
2583 redef class AImpliesExpr
2584 redef fun expr(v)
2585 do
2586 var res = v.new_var(self.mtype.as(not null))
2587 var i1 = v.expr_bool(self.n_expr)
2588 v.add("if (!{i1}) \{")
2589 v.add("{res} = 1;")
2590 v.add("\} else \{")
2591 var i2 = v.expr_bool(self.n_expr2)
2592 v.add("{res} = {i2};")
2593 v.add("\}")
2594 return res
2595 end
2596 end
2597
2598 redef class AAndExpr
2599 redef fun expr(v)
2600 do
2601 var res = v.new_var(self.mtype.as(not null))
2602 var i1 = v.expr_bool(self.n_expr)
2603 v.add("if (!{i1}) \{")
2604 v.add("{res} = 0;")
2605 v.add("\} else \{")
2606 var i2 = v.expr_bool(self.n_expr2)
2607 v.add("{res} = {i2};")
2608 v.add("\}")
2609 return res
2610 end
2611 end
2612
2613 redef class ANotExpr
2614 redef fun expr(v)
2615 do
2616 var cond = v.expr_bool(self.n_expr)
2617 return v.new_expr("!{cond}", self.mtype.as(not null))
2618 end
2619 end
2620
2621 redef class AOrElseExpr
2622 redef fun expr(v)
2623 do
2624 var res = v.new_var(self.mtype.as(not null))
2625 var i1 = v.expr(self.n_expr, null)
2626 v.add("if ({i1}!=NULL) \{")
2627 v.assign(res, i1)
2628 v.add("\} else \{")
2629 var i2 = v.expr(self.n_expr2, null)
2630 v.assign(res, i2)
2631 v.add("\}")
2632 return res
2633 end
2634 end
2635
2636 redef class AIntExpr
2637 redef fun expr(v) do return v.new_expr("{self.value.to_s}", self.mtype.as(not null))
2638 end
2639
2640 redef class AFloatExpr
2641 redef fun expr(v) do return v.new_expr("{self.n_float.text}", self.mtype.as(not null)) # FIXME use value, not n_float
2642 end
2643
2644 redef class ACharExpr
2645 redef fun expr(v) do return v.new_expr("'{self.value.to_s.escape_to_c}'", self.mtype.as(not null))
2646 end
2647
2648 redef class AArrayExpr
2649 redef fun expr(v)
2650 do
2651 var mtype = self.mtype.as(MClassType).arguments.first
2652 var array = new Array[RuntimeVariable]
2653 for nexpr in self.n_exprs.n_exprs do
2654 var i = v.expr(nexpr, mtype)
2655 array.add(i)
2656 end
2657 return v.array_instance(array, mtype)
2658 end
2659 end
2660
2661 redef class AStringFormExpr
2662 redef fun expr(v) do return v.string_instance(self.value.as(not null))
2663 end
2664
2665 redef class ASuperstringExpr
2666 redef fun expr(v)
2667 do
2668 var array = new Array[RuntimeVariable]
2669 for ne in self.n_exprs do
2670 if ne isa AStringFormExpr and ne.value == "" then continue # skip empty sub-strings
2671 var i = v.expr(ne, null)
2672 array.add(i)
2673 end
2674 var a = v.array_instance(array, v.object_type)
2675 var res = v.send(v.get_property("to_s", a.mtype), [a])
2676 return res
2677 end
2678 end
2679
2680 redef class ACrangeExpr
2681 redef fun expr(v)
2682 do
2683 var i1 = v.expr(self.n_expr, null)
2684 var i2 = v.expr(self.n_expr2, null)
2685 var mtype = self.mtype.as(MClassType)
2686 var res = v.init_instance(mtype)
2687 v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2688 return res
2689 end
2690 end
2691
2692 redef class AOrangeExpr
2693 redef fun expr(v)
2694 do
2695 var i1 = v.expr(self.n_expr, null)
2696 var i2 = v.expr(self.n_expr2, null)
2697 var mtype = self.mtype.as(MClassType)
2698 var res = v.init_instance(mtype)
2699 v.compile_callsite(init_callsite.as(not null), [res, i1, i2])
2700 return res
2701 end
2702 end
2703
2704 redef class ATrueExpr
2705 redef fun expr(v) do return v.new_expr("1", self.mtype.as(not null))
2706 end
2707
2708 redef class AFalseExpr
2709 redef fun expr(v) do return v.new_expr("0", self.mtype.as(not null))
2710 end
2711
2712 redef class ANullExpr
2713 redef fun expr(v) do return v.new_expr("NULL", self.mtype.as(not null))
2714 end
2715
2716 redef class AIsaExpr
2717 redef fun expr(v)
2718 do
2719 var i = v.expr(self.n_expr, null)
2720 return v.type_test(i, self.cast_type.as(not null), "isa")
2721 end
2722 end
2723
2724 redef class AAsCastExpr
2725 redef fun expr(v)
2726 do
2727 var i = v.expr(self.n_expr, null)
2728 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2729
2730 v.add_cast(i, self.mtype.as(not null), "as")
2731 return i
2732 end
2733 end
2734
2735 redef class AAsNotnullExpr
2736 redef fun expr(v)
2737 do
2738 var i = v.expr(self.n_expr, null)
2739 if v.compiler.modelbuilder.toolcontext.opt_no_check_assert.value then return i
2740
2741 if i.mtype.ctype != "val*" then return i
2742
2743 v.add("if (unlikely({i} == NULL)) \{")
2744 v.add_abort("Cast failed")
2745 v.add("\}")
2746 return i
2747 end
2748 end
2749
2750 redef class AParExpr
2751 redef fun expr(v) do return v.expr(self.n_expr, null)
2752 end
2753
2754 redef class AOnceExpr
2755 redef fun expr(v)
2756 do
2757 var mtype = self.mtype.as(not null)
2758 var name = v.get_name("varonce")
2759 var guard = v.get_name(name + "_guard")
2760 v.add_decl("static {mtype.ctype} {name};")
2761 v.add_decl("static int {guard};")
2762 var res = v.new_var(mtype)
2763 v.add("if ({guard}) \{")
2764 v.add("{res} = {name};")
2765 v.add("\} else \{")
2766 var i = v.expr(self.n_expr, mtype)
2767 v.add("{res} = {i};")
2768 v.add("{name} = {res};")
2769 v.add("{guard} = 1;")
2770 v.add("\}")
2771 return res
2772 end
2773 end
2774
2775 redef class ASendExpr
2776 redef fun expr(v)
2777 do
2778 var recv = v.expr(self.n_expr, null)
2779 var callsite = self.callsite.as(not null)
2780 var args = v.varargize(callsite.mpropdef, recv, self.raw_arguments)
2781 return v.compile_callsite(callsite, args)
2782 end
2783 end
2784
2785 redef class ASendReassignFormExpr
2786 redef fun stmt(v)
2787 do
2788 var recv = v.expr(self.n_expr, null)
2789 var callsite = self.callsite.as(not null)
2790 var args = v.varargize(callsite.mpropdef, recv, self.raw_arguments)
2791
2792 var value = v.expr(self.n_value, null)
2793
2794 var left = v.compile_callsite(callsite, args)
2795 assert left != null
2796
2797 var res = v.compile_callsite(self.reassign_callsite.as(not null), [left, value])
2798 assert res != null
2799
2800 args.add(res)
2801 v.compile_callsite(self.write_callsite.as(not null), args)
2802 end
2803 end
2804
2805 redef class ASuperExpr
2806 redef fun expr(v)
2807 do
2808 var recv = v.frame.arguments.first
2809
2810 var callsite = self.callsite
2811 if callsite != null then
2812 var args = v.varargize(callsite.mpropdef, recv, self.n_args.n_exprs)
2813
2814 # Add additional arguments for the super init call
2815 if args.length == 1 then
2816 for i in [0..callsite.msignature.arity[ do
2817 args.add(v.frame.arguments[i+1])
2818 end
2819 end
2820 # Super init call
2821 var res = v.compile_callsite(callsite, args)
2822 return res
2823 end
2824
2825 var mpropdef = self.mpropdef.as(not null)
2826 var args = v.varargize(mpropdef, recv, self.n_args.n_exprs)
2827 if args.length == 1 then
2828 args = v.frame.arguments
2829 end
2830
2831 # stantard call-next-method
2832 return v.supercall(mpropdef, recv.mtype.as(MClassType), args)
2833 end
2834 end
2835
2836 redef class ANewExpr
2837 redef fun expr(v)
2838 do
2839 var mtype = self.recvtype
2840 assert mtype != null
2841 var recv
2842 var ctype = mtype.ctype
2843 if mtype.mclass.name == "NativeArray" then
2844 assert self.n_args.n_exprs.length == 1
2845 var l = v.expr(self.n_args.n_exprs.first, null)
2846 assert mtype isa MGenericType
2847 var elttype = mtype.arguments.first
2848 return v.native_array_instance(elttype, l)
2849 else if ctype == "val*" then
2850 recv = v.init_instance(mtype)
2851 else if ctype == "char*" then
2852 recv = v.new_expr("NULL/*special!*/", mtype)
2853 else
2854 recv = v.new_expr("({ctype})0/*special!*/", mtype)
2855 end
2856
2857 var callsite = self.callsite.as(not null)
2858 var args = v.varargize(callsite.mpropdef, recv, self.n_args.n_exprs)
2859 var res2 = v.compile_callsite(callsite, args)
2860 if res2 != null then
2861 #self.debug("got {res2} from {mproperty}. drop {recv}")
2862 return res2
2863 end
2864 return recv
2865 end
2866 end
2867
2868 redef class AAttrExpr
2869 redef fun expr(v)
2870 do
2871 var recv = v.expr(self.n_expr, null)
2872 var mproperty = self.mproperty.as(not null)
2873 return v.read_attribute(mproperty, recv)
2874 end
2875 end
2876
2877 redef class AAttrAssignExpr
2878 redef fun expr(v)
2879 do
2880 var recv = v.expr(self.n_expr, null)
2881 var i = v.expr(self.n_value, null)
2882 var mproperty = self.mproperty.as(not null)
2883 v.write_attribute(mproperty, recv, i)
2884 return i
2885 end
2886 end
2887
2888 redef class AAttrReassignExpr
2889 redef fun stmt(v)
2890 do
2891 var recv = v.expr(self.n_expr, null)
2892 var value = v.expr(self.n_value, null)
2893 var mproperty = self.mproperty.as(not null)
2894 var attr = v.read_attribute(mproperty, recv)
2895 var res = v.compile_callsite(self.reassign_callsite.as(not null), [attr, value])
2896 assert res != null
2897 v.write_attribute(mproperty, recv, res)
2898 end
2899 end
2900
2901 redef class AIssetAttrExpr
2902 redef fun expr(v)
2903 do
2904 var recv = v.expr(self.n_expr, null)
2905 var mproperty = self.mproperty.as(not null)
2906 return v.isset_attribute(mproperty, recv)
2907 end
2908 end
2909
2910 redef class ADebugTypeExpr
2911 redef fun stmt(v)
2912 do
2913 # do nothing
2914 end
2915 end
2916
2917 # Utils
2918
2919 redef class Array[E]
2920 # Return a new `Array` with the elements only contened in self and not in `o`
2921 fun -(o: Array[E]): Array[E] do
2922 var res = new Array[E]
2923 for e in self do if not o.has(e) then res.add(e)
2924 return res
2925 end
2926 end
2927
2928 redef class MModule
2929 # All `MProperty` associated to all `MClassDef` of `mclass`
2930 fun properties(mclass: MClass): Set[MProperty] do
2931 if not self.properties_cache.has_key(mclass) then
2932 var properties = new HashSet[MProperty]
2933 var parents = new Array[MClass]
2934 if self.flatten_mclass_hierarchy.has(mclass) then
2935 parents.add_all(mclass.in_hierarchy(self).direct_greaters)
2936 end
2937 for parent in parents do
2938 properties.add_all(self.properties(parent))
2939 end
2940 for mclassdef in mclass.mclassdefs do
2941 if not self.in_importation <= mclassdef.mmodule then continue
2942 for mprop in mclassdef.intro_mproperties do
2943 properties.add(mprop)
2944 end
2945 end
2946 self.properties_cache[mclass] = properties
2947 end
2948 return properties_cache[mclass]
2949 end
2950 private var properties_cache: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
2951
2952 # Write FFI and nitni results to file
2953 fun finalize_ffi(c: AbstractCompiler) do end
2954
2955 # Give requided addinional system libraries (as given to LD_LIBS)
2956 # Note: can return null instead of an empty set
2957 fun collect_linker_libs: nullable Set[String] do return null
2958 end
2959
2960 # Create a tool context to handle options and paths
2961 var toolcontext = new ToolContext
2962
2963 toolcontext.tooldescription = "Usage: nitc [OPTION]... file.nit...\nCompiles Nit programs."
2964
2965 # We do not add other options, so process them now!
2966 toolcontext.process_options(args)
2967
2968 # We need a model to collect stufs
2969 var model = new Model
2970 # An a model builder to parse files
2971 var modelbuilder = new ModelBuilder(model, toolcontext)
2972
2973 var arguments = toolcontext.option_context.rest
2974 if arguments.length > 1 and toolcontext.opt_output.value != null then
2975 print "Error: --output needs a single source file. Do you prefer --dir?"
2976 exit 1
2977 end
2978
2979 # Here we load an process all modules passed on the command line
2980 var mmodules = modelbuilder.parse(arguments)
2981
2982 if mmodules.is_empty then return
2983 modelbuilder.run_phases
2984
2985 for mmodule in mmodules do
2986 toolcontext.info("*** PROCESS {mmodule} ***", 1)
2987 var ms = [mmodule]
2988 toolcontext.run_global_phases(ms)
2989 end