1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
18 module abstract_compiler
22 import auto_super_init
24 # Add compiling options
25 redef class ToolContext
27 var opt_output
: OptionString = new OptionString("Output file", "-o", "--output")
29 var opt_no_cc
: OptionBool = new OptionBool("Do not invoke C compiler", "--no-cc")
31 var opt_cc_path
: OptionArray = new OptionArray("Set include path for C header files (may be used more than once)", "--cc-path")
33 var opt_make_flags
: OptionString = new OptionString("Additional options to make", "--make-flags")
35 var opt_hardening
: OptionBool = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
37 var opt_no_shortcut_range
: OptionBool = new OptionBool("Always insantiate a range and its iterator on 'for' loops", "--no-shortcut-range")
38 # --no-check-covariance
39 var opt_no_check_covariance
: OptionBool = new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
40 # --no-check-initialization
41 var opt_no_check_initialization
: OptionBool = new OptionBool("Disable isset tests at the end of constructors (dangerous)", "--no-check-initialization")
43 var opt_no_check_assert
: OptionBool = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
45 var opt_no_check_autocast
: OptionBool = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
47 var opt_no_check_other
: OptionBool = new OptionBool("Disable implicit tests: unset attribute, null receiver (dangerous)", "--no-check-other")
48 # --typing-test-metrics
49 var opt_typing_test_metrics
: OptionBool = new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
54 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_make_flags
, self.opt_hardening
, self.opt_no_shortcut_range
)
55 self.option_context
.add_option
(self.opt_no_check_covariance
, self.opt_no_check_initialization
, self.opt_no_check_assert
, self.opt_no_check_autocast
, self.opt_no_check_other
)
56 self.option_context
.add_option
(self.opt_typing_test_metrics
)
60 redef class ModelBuilder
61 # The list of directories to search for included C headers (-I for C compilers)
62 # The list is initially set with :
63 # * the toolcontext --cc-path option
64 # * the NIT_CC_PATH environment variable
65 # * some heuristics including the NIT_DIR environment variable and the progname of the process
66 # Path can be added (or removed) by the client
67 var cc_paths
= new Array[String]
69 redef init(model
, toolcontext
)
73 # Look for the the Nit clib path
74 var path_env
= "NIT_DIR".environ
75 if not path_env
.is_empty
then
76 var libname
= "{path_env}/clib"
77 if libname
.file_exists
then cc_paths
.add
(libname
)
80 var libname
= "{sys.program_name.dirname}/../clib"
81 if libname
.file_exists
then cc_paths
.add
(libname
.simplify_path
)
83 if cc_paths
.is_empty
then
84 toolcontext
.error
(null, "Cannot determine the nit clib path. define envvar NIT_DIR.")
87 # Add user defined cc_paths
88 cc_paths
.append
(toolcontext
.opt_cc_path
.value
)
90 path_env
= "NIT_CC_PATH".environ
91 if not path_env
.is_empty
then
92 cc_paths
.append
(path_env
.split_with
(':'))
97 protected fun write_and_make
(compiler
: AbstractCompiler)
99 var mainmodule
= compiler
.mainmodule
101 # Generate the .h and .c files
102 # A single C file regroups many compiled rumtime functions
103 # 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
105 self.toolcontext
.info
("*** WRITING C ***", 1)
109 var outname
= self.toolcontext
.opt_output
.value
110 if outname
== null then
111 outname
= "{mainmodule.name}"
114 var hfilename
= compiler
.header
.file
.name
+ ".h"
115 var hfilepath
= ".nit_compile/{hfilename}"
116 var h
= new OFStream.open
(hfilepath
)
117 for l
in compiler
.header
.decl_lines
do
121 for l
in compiler
.header
.lines
do
127 var cfiles
= new Array[String]
129 for f
in compiler
.files
do
131 var hfile
: nullable OFStream = null
133 var cfilename
= ".nit_compile/{f.name}.0.h"
134 hfile
= new OFStream.open
(cfilename
)
135 hfile
.write
"#include \"{hfilename}\
"\n"
136 for key
in f
.required_declarations
do
137 if not compiler
.provided_declarations
.has_key
(key
) then
138 print
"No provided declaration for {key}"
141 hfile
.write compiler
.provided_declarations
[key
]
145 var file
: nullable OFStream = null
146 for vis
in f
.writers
do
147 if vis
== compiler
.header
then continue
148 var total_lines
= vis
.lines
.length
+ vis
.decl_lines
.length
149 if total_lines
== 0 then continue
151 if file
== null or count
> 10000 then
153 if file
!= null then file
.close
154 cfilename
= ".nit_compile/{f.name}.{i}.c"
155 self.toolcontext
.info
("new C source files to compile: {cfilename}", 3)
156 cfiles
.add
(cfilename
)
157 file
= new OFStream.open
(cfilename
)
158 file
.write
"#include \"{f.name}.0.h\
"\n"
161 for l
in vis
.decl_lines
do
165 for l
in vis
.lines
do
170 if file
!= null then file
.close
173 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
175 # Generate the Makefile
177 var makename
= ".nit_compile/{mainmodule.name}.mk"
178 var makefile
= new OFStream.open
(makename
)
182 #p = "..".join_path(p)
183 cc_includes
+= " -I \"" + p + "\
""
185 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nCINCL = {cc_includes}\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
186 makefile
.write
("all: {outname}\n\n")
188 var ofiles
= new Array[String]
189 # Compile each generated file
191 var o
= f
.strip_extension
(".c") + ".o"
192 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) $(CINCL) -D NONITCNI -c -o {o} {f}\n\n")
196 # Add gc_choser.h to aditionnal bodies
197 var gc_chooser
= new ExternCFile("{cc_paths.first}/gc_chooser.c", "-DWITH_LIBGC")
198 compiler
.extern_bodies
.add
(gc_chooser
)
200 # Compile each required extern body into a specific .o
201 for f
in compiler
.extern_bodies
do
202 var basename
= f
.filename
.basename
(".c")
203 var o
= ".nit_compile/{basename}.extern.o"
204 makefile
.write
("{o}: {f.filename}\n\t$(CC) $(CFLAGS) -D NONITCNI {f.cflags} -c -o {o} {f.filename}\n\n")
209 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
211 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
213 self.toolcontext
.info
("Generated makefile: {makename}", 2)
216 self.toolcontext
.info
("*** END WRITING C: {time1-time0} ***", 2)
218 # Execute the Makefile
220 if self.toolcontext
.opt_no_cc
.value
then return
223 self.toolcontext
.info
("*** COMPILING C ***", 1)
224 var makeflags
= self.toolcontext
.opt_make_flags
.value
225 if makeflags
== null then makeflags
= ""
226 self.toolcontext
.info
("make -B -f {makename} -j 4 {makeflags}", 2)
229 if self.toolcontext
.verbose_level
>= 3 then
230 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1")
232 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
235 toolcontext
.error
(null, "make failed! Error code: {res}.")
239 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
243 # Singleton that store the knowledge about the compilation process
244 abstract class AbstractCompiler
245 type VISITOR: AbstractCompilerVisitor
247 # The main module of the program currently compiled
248 # Is assigned during the separate compilation
249 var mainmodule
: MModule writable
251 # The real main module of the program
252 var realmainmodule
: MModule
254 # The modeulbuilder used to know the model and the AST
255 var modelbuilder
: ModelBuilder protected writable
257 # Is hardening asked? (see --hardening)
258 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
260 init(mainmodule
: MModule, modelbuilder
: ModelBuilder)
262 self.mainmodule
= mainmodule
263 self.realmainmodule
= mainmodule
264 self.modelbuilder
= modelbuilder
267 # Force the creation of a new file
268 # The point is to avoid contamination between must-be-compiled-separately files
269 fun new_file
(name
: String): CodeFile
271 var f
= new CodeFile(name
)
276 # The list of all associated files
277 # Used to generate .c files
278 var files
: List[CodeFile] = new List[CodeFile]
280 # Initialize a visitor specific for a compiler engine
281 fun new_visitor
: VISITOR is abstract
283 # Where global declaration are stored (the main .h)
284 var header
: CodeWriter writable
286 # Provide a declaration that can be requested (before or latter) by a visitor
287 fun provide_declaration
(key
: String, s
: String)
289 if self.provided_declarations
.has_key
(key
) then
290 assert self.provided_declarations
[key
] == s
292 self.provided_declarations
[key
] = s
295 private var provided_declarations
= new HashMap[String, String]
298 # This method call compile_header_strucs method that has to be refined
299 fun compile_header
do
301 self.header
.add_decl
("#include <stdlib.h>")
302 self.header
.add_decl
("#include <stdio.h>")
303 self.header
.add_decl
("#include <string.h>")
304 self.header
.add_decl
("#include <gc_chooser.h>")
306 compile_header_structs
308 # Global variable used by the legacy native interface
309 self.header
.add_decl
("extern int glob_argc;")
310 self.header
.add_decl
("extern char **glob_argv;")
311 self.header
.add_decl
("extern val *glob_sys;")
314 # Declaration of structures the live Nit types
315 protected fun compile_header_structs
is abstract
317 # Generate the main C function.
319 # * allocate the Sys object if it exists
320 # * call init if is exists
321 # * call main if it exists
322 fun compile_main_function
324 var v
= self.new_visitor
325 v
.add_decl
("int glob_argc;")
326 v
.add_decl
("char **glob_argv;")
327 v
.add_decl
("val *glob_sys;")
329 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
330 for tag
in count_type_test_tags
do
331 v
.add_decl
("long count_type_test_resolved_{tag};")
332 v
.add_decl
("long count_type_test_unresolved_{tag};")
333 v
.add_decl
("long count_type_test_skipped_{tag};")
334 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
335 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
336 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
339 v
.add_decl
("int main(int argc, char** argv) \{")
340 v
.add
("glob_argc = argc; glob_argv = argv;")
341 v
.add
("initialize_gc_option();")
342 var main_type
= mainmodule
.sys_type
343 if main_type
!= null then
344 var mainmodule
= v
.compiler
.mainmodule
345 var glob_sys
= v
.init_instance
(main_type
)
346 v
.add
("glob_sys = {glob_sys};")
347 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
.mclass
)
348 if main_init
!= null then
349 v
.send
(main_init
, [glob_sys
])
351 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
.mclass
)
352 if main_method
!= null then
353 v
.send
(main_method
, [glob_sys
])
357 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
358 v
.add_decl
("long count_type_test_resolved_total = 0;")
359 v
.add_decl
("long count_type_test_unresolved_total = 0;")
360 v
.add_decl
("long count_type_test_skipped_total = 0;")
361 v
.add_decl
("long count_type_test_total_total = 0;")
362 for tag
in count_type_test_tags
do
363 v
.add_decl
("long count_type_test_total_{tag};")
364 v
.add
("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
365 v
.add
("count_type_test_resolved_total += count_type_test_resolved_{tag};")
366 v
.add
("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
367 v
.add
("count_type_test_skipped_total += count_type_test_skipped_{tag};")
368 v
.add
("count_type_test_total_total += count_type_test_total_{tag};")
370 v
.add
("printf(\"# dynamic count_type_test: total %l\\n\");")
371 v
.add
("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\
");")
372 var tags
= count_type_test_tags
.to_a
375 v
.add
("printf(\"{tag}\
");")
376 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
377 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
378 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
379 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\\n\
", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
386 # List of additional .c files required to compile (native interface)
387 var extern_bodies
= new Array[ExternCFile]
389 # This is used to avoid adding an extern file more than once
390 private var seen_extern
= new ArraySet[String]
392 # Generate code that check if an instance is correctly initialized
393 fun generate_check_init_instance
(mtype
: MClassType) is abstract
395 # Generate code that initialize the attributes on a new instance
396 fun generate_init_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
398 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
399 self.mainmodule
.linearize_mclassdefs
(cds
)
401 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
402 for npropdef
in n
.n_propdefs
do
403 if npropdef
isa AAttrPropdef then
404 npropdef
.init_expr
(v
, recv
)
410 # Generate code that check if an attribute is correctly initialized
411 fun generate_check_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
413 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
414 self.mainmodule
.linearize_mclassdefs
(cds
)
416 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
417 for npropdef
in n
.n_propdefs
do
418 if npropdef
isa AAttrPropdef then
419 npropdef
.check_expr
(v
, recv
)
427 var count_type_test_tags
: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
428 var count_type_test_resolved
: HashMap[String, Int] = init_count_type_test_tags
429 var count_type_test_unresolved
: HashMap[String, Int] = init_count_type_test_tags
430 var count_type_test_skipped
: HashMap[String, Int] = init_count_type_test_tags
432 protected fun init_count_type_test_tags
: HashMap[String, Int]
434 var res
= new HashMap[String, Int]
435 for tag
in count_type_test_tags
do
441 # Display stats about compilation process
443 # * type tests against resolved types (x isa Collection[Animal])
444 # * type tests against unresolved types (x isa Collection[E])
445 # * type tests skipped
450 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
451 print
"# static count_type_test"
452 print
"\tresolved:\tunresolved\tskipped\ttotal"
453 var count_type_test_total
= init_count_type_test_tags
454 count_type_test_resolved
["total"] = 0
455 count_type_test_unresolved
["total"] = 0
456 count_type_test_skipped
["total"] = 0
457 count_type_test_total
["total"] = 0
458 for tag
in count_type_test_tags
do
459 count_type_test_total
[tag
] = count_type_test_resolved
[tag
] + count_type_test_unresolved
[tag
] + count_type_test_skipped
[tag
]
460 count_type_test_resolved
["total"] += count_type_test_resolved
[tag
]
461 count_type_test_unresolved
["total"] += count_type_test_unresolved
[tag
]
462 count_type_test_skipped
["total"] += count_type_test_skipped
[tag
]
463 count_type_test_total
["total"] += count_type_test_total
[tag
]
465 var count_type_test
= count_type_test_total
["total"]
466 var tags
= count_type_test_tags
.to_a
470 printn
"\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
471 printn
"\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
472 printn
"\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
473 printn
"\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
480 # Avoid division by zero by returning the string "n/a"
481 fun div
(a
,b
:Int):String
483 if b
== 0 then return "n/a"
484 return ((a
*10000/b
).to_f
/ 100.0).to_precision
(2)
488 # A file unit (may be more than one file if
489 # A file unit aim to be autonomous and is made or one or more `CodeWriter`s
492 var writers
= new Array[CodeWriter]
493 var required_declarations
= new HashSet[String]
496 # Where to store generated lines
499 var lines
: List[String] = new List[String]
500 var decl_lines
: List[String] = new List[String]
502 # Add a line in the main part of the generated C
503 fun add
(s
: String) do self.lines
.add
(s
)
506 # (used for local or global declaration)
507 fun add_decl
(s
: String) do self.decl_lines
.add
(s
)
512 file
.writers
.add
(self)
516 # A visitor on the AST of property definition that generate the C code.
517 abstract class AbstractCompilerVisitor
519 type COMPILER: AbstractCompiler
521 # The associated compiler
522 var compiler
: COMPILER
524 # The current visited AST node
525 var current_node
: nullable ANode writable = null
528 var frame
: nullable Frame writable
530 # Alias for self.compiler.mainmodule.object_type
531 fun object_type
: MClassType do return self.compiler
.mainmodule
.object_type
533 # Alias for self.compiler.mainmodule.bool_type
534 fun bool_type
: MClassType do return self.compiler
.mainmodule
.bool_type
536 var writer
: CodeWriter
538 init(compiler
: COMPILER)
540 self.compiler
= compiler
541 self.writer
= new CodeWriter(compiler
.files
.last
)
544 # Force to get the primitive class named `name' or abort
545 fun get_class
(name
: String): MClass do return self.compiler
.mainmodule
.get_primitive_class
(name
)
547 # Force to get the primitive property named `name' in the instance `recv' or abort
548 fun get_property
(name
: String, recv
: MType): MMethod
550 assert recv
isa MClassType
551 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
.mclass
, self.compiler
.mainmodule
)
554 fun compile_callsite
(callsite
: CallSite, args
: Array[RuntimeVariable]): nullable RuntimeVariable
556 return self.send
(callsite
.mproperty
, args
)
559 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable]) is abstract
561 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable]) is abstract
563 # Transform varargs, in raw arguments, into a single argument of type Array
564 # Note: this method modify the given `args`
565 # If there is no vararg, then `args` is not modified.
566 fun varargize
(mpropdef
: MPropDef, msignature
: MSignature, args
: Array[RuntimeVariable])
568 var recv
= args
.first
569 var vararg_rank
= msignature
.vararg_rank
570 if vararg_rank
>= 0 then
571 assert args
.length
>= msignature
.arity
+ 1 # because of self
573 args
= new Array[RuntimeVariable]
575 args
.add
(rawargs
.first
) # recv
577 for i
in [0..vararg_rank
[ do
578 args
.add
(rawargs
[i
+1])
581 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-msignature
.arity
582 var vararg
= new Array[RuntimeVariable]
583 for i
in [vararg_rank
..vararg_lastrank
] do
584 vararg
.add
(rawargs
[i
+1])
587 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
588 args
.add
(self.vararg_instance
(mpropdef
, recv
, vararg
, elttype
))
590 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
591 args
.add
(rawargs
[i
+1])
594 rawargs
.add_all
(args
)
600 # Anchor a type to the main module and the current receiver
601 fun anchor
(mtype
: MType): MType
603 if not mtype
.need_anchor
then return mtype
604 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
607 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
609 if not mtype
.need_anchor
then return mtype
610 return mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
613 # Unsafely cast a value to a new type
614 # ie the result share the same C variable but my have a different mcasttype
615 # NOTE: if the adaptation is useless then `value' is returned as it.
616 # ENSURE: return.name == value.name
617 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
619 mtype
= self.anchor
(mtype
)
620 var valmtype
= value
.mcasttype
621 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
625 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
626 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
629 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
634 # Generate a super call from a method definition
635 fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
637 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable]) is abstract
639 # Box or unbox a value to another type iff a C type conversion is needed
640 # ENSURE: result.mtype.ctype == mtype.ctype
641 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
643 # Generate a polymorphic subtype test
644 fun type_test
(value
: RuntimeVariable, mtype
: MType, tag
: String): RuntimeVariable is abstract
646 # Generate the code required to dynamically check if 2 objects share the same runtime type
647 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
649 # Generate a Nit "is" for two runtime_variables
650 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
654 # Generate a static call on a method definition
655 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
657 # Generate a polymorphic send for the method `m' and the arguments `args'
658 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
660 # Generate a monomorphic send for the method `m', the type `t' and the arguments `args'
661 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
663 assert t
isa MClassType
664 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
665 return self.call
(propdef
, t
, args
)
668 # Attributes handling
670 # Generate a polymorphic attribute is_set test
671 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
673 # Generate a polymorphic attribute read
674 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
676 # Generate a polymorphic attribute write
677 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable) is abstract
681 # Add a check and an abort for a null reciever if needed
682 fun check_recv_notnull
(recv
: RuntimeVariable)
684 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
686 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
688 self.add
("if ({recv} == NULL) \{")
689 self.add_abort
("Reciever is null")
694 # Generate a check-init-instance
695 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType) is abstract
699 private var names
: HashSet[String] = new HashSet[String]
700 private var last
: Int = 0
702 # Return a new name based on `s' and unique in the visitor
703 fun get_name
(s
: String): String
705 if not self.names
.has
(s
) then
709 var i
= self.last
+ 1
712 if not self.names
.has
(s2
) then
721 # Return an unique and stable identifier associated with an escapemark
722 fun escapemark_name
(e
: nullable EscapeMark): String
725 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
727 if name
== null then name
= "label"
728 name
= get_name
(name
)
729 escapemark_names
[e
] = name
733 private var escapemark_names
= new HashMap[EscapeMark, String]
735 # Return a "const char*" variable associated to the classname of the dynamic type of an object
736 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
737 fun class_name_string
(value
: RuntimeVariable): String is abstract
741 protected var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
743 # Return the local runtime_variable associated to a Nit local variable
744 fun variable
(variable
: Variable): RuntimeVariable
746 if self.variables
.has_key
(variable
) then
747 return self.variables
[variable
]
749 var name
= self.get_name
("var_{variable.name}")
750 var mtype
= variable
.declared_type
.as(not null)
751 mtype
= self.anchor
(mtype
)
752 var res
= new RuntimeVariable(name
, mtype
, mtype
)
753 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
754 self.variables
[variable
] = res
759 # Return a new uninitialized local runtime_variable
760 fun new_var
(mtype
: MType): RuntimeVariable
762 mtype
= self.anchor
(mtype
)
763 var name
= self.get_name
("var")
764 var res
= new RuntimeVariable(name
, mtype
, mtype
)
765 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
769 # Return a new uninitialized named runtime_variable
770 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
772 mtype
= self.anchor
(mtype
)
773 var res
= new RuntimeVariable(name
, mtype
, mtype
)
774 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
778 # Correctly assign a left and a right value
779 # Boxing and unboxing is performed if required
780 fun assign
(left
, right
: RuntimeVariable)
782 right
= self.autobox
(right
, left
.mtype
)
783 self.add
("{left} = {right};")
788 # Generate a alloc-instance + init-attributes
789 fun init_instance
(mtype
: MClassType): RuntimeVariable is abstract
791 # Generate an integer value
792 fun int_instance
(value
: Int): RuntimeVariable
794 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
795 self.add
("{res} = {value};")
799 # Generate a string value
800 fun string_instance
(string
: String): RuntimeVariable
802 var mtype
= self.get_class
("String").mclass_type
803 var name
= self.get_name
("varonce")
804 self.add_decl
("static {mtype.ctype} {name};")
805 var res
= self.new_var
(mtype
)
806 self.add
("if ({name}) \{")
807 self.add
("{res} = {name};")
808 self.add
("\} else \{")
809 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
810 self.add
("{nat} = \"{string.escape_to_c}\
";")
811 var res2
= self.init_instance
(mtype
)
812 self.add
("{res} = {res2};")
813 var length
= self.int_instance
(string
.length
)
814 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
815 self.check_init_instance
(res
, mtype
)
816 self.add
("{name} = {res};")
821 # Generate an array value
822 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
824 # Get an instance of a array for a vararg
825 fun vararg_instance
(mpropdef
: MPropDef, recv
: RuntimeVariable, varargs
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
829 # Add a line in the main part of the generated C
830 fun add
(s
: String) do self.writer
.lines
.add
(s
)
833 # (used for local or global declaration)
834 fun add_decl
(s
: String) do self.writer
.decl_lines
.add
(s
)
836 # Request the presence of a global declaration
837 fun require_declaration
(key
: String)
839 self.writer
.file
.required_declarations
.add
(key
)
842 # Add a declaration in the local-header
843 # The declaration is ensured to be present once
844 fun declare_once
(s
: String)
846 self.compiler
.provide_declaration
(s
, s
)
847 self.require_declaration
(s
)
850 # look for a needed .h and .c file for a given .nit source-file
851 # FIXME: bad API, parameter should be a MModule, not its source-file
852 fun add_extern
(file
: String)
854 file
= file
.strip_extension
(".nit")
855 var tryfile
= file
+ ".nit.h"
856 if tryfile
.file_exists
then
857 self.declare_once
("#include \"{"..".join_path(tryfile)}\
"")
859 tryfile
= file
+ "_nit.h"
860 if tryfile
.file_exists
then
861 self.declare_once
("#include \"{"..".join_path(tryfile)}\
"")
864 if self.compiler
.seen_extern
.has
(file
) then return
865 self.compiler
.seen_extern
.add
(file
)
866 tryfile
= file
+ ".nit.c"
867 if not tryfile
.file_exists
then
868 tryfile
= file
+ "_nit.c"
869 if not tryfile
.file_exists
then return
871 var f
= new ExternCFile(tryfile
, "")
872 self.compiler
.extern_bodies
.add
(f
)
875 # Return a new local runtime_variable initialized with the C expression `cexpr'.
876 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
878 var res
= new_var
(mtype
)
879 self.add
("{res} = {cexpr};")
883 # Generate generic abort
884 # used by aborts, asserts, casts, etc.
885 fun add_abort
(message
: String)
887 if self.current_node
!= null and self.current_node
.location
.file
!= null then
888 self.add
("fprintf(stderr, \"Runtime error
: %s
(%s
:%d
)\\n\
", \"{message.escape_to_c}\
", \"{self.current_node.location.file.filename.escape_to_c}\
", {current_node.location.line_start});")
890 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
895 # Generate a return with the value `s'
896 fun ret
(s
: RuntimeVariable)
898 self.assign
(self.frame
.returnvar
.as(not null), s
)
899 self.add
("goto {self.frame.returnlabel.as(not null)};")
902 # Compile a statement (if any)
903 fun stmt
(nexpr
: nullable AExpr)
905 if nexpr
== null then return
906 var old
= self.current_node
907 self.current_node
= nexpr
909 self.current_node
= old
912 # Compile an expression an return its result
913 # `mtype` is the expected return type, pass null if no specific type is expected.
914 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
916 var old
= self.current_node
917 self.current_node
= nexpr
918 var res
= nexpr
.expr
(self).as(not null)
919 if mtype
!= null then
920 mtype
= self.anchor
(mtype
)
921 res
= self.autobox
(res
, mtype
)
923 res
= autoadapt
(res
, nexpr
.mtype
.as(not null))
924 var implicit_cast_to
= nexpr
.implicit_cast_to
925 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
926 var castres
= self.type_test
(res
, implicit_cast_to
, "auto")
927 self.add
("if (!{castres}) \{")
928 self.add_abort
("Cast failed")
930 res
= autoadapt
(res
, implicit_cast_to
)
932 self.current_node
= old
936 # Alias for `self.expr(nexpr, self.bool_type)'
937 fun expr_bool
(nexpr
: AExpr): RuntimeVariable do return expr
(nexpr
, bool_type
)
939 # Safely show a debug message on the current node and repeat the message in the C code as a comment
940 fun debug
(message
: String)
942 var node
= self.current_node
948 self.add
("/* DEBUG: {message} */")
952 # A C function associated to a Nit method
953 # Because of customization, a given Nit method can be compiler more that once
954 abstract class AbstractRuntimeFunction
956 type COMPILER: AbstractCompiler
957 type VISITOR: AbstractCompilerVisitor
959 # The associated Nit method
960 var mmethoddef
: MMethodDef
962 # The mangled c name of the runtime_function
963 # Subclasses should redefine `build_c_name` instead
966 var res
= self.c_name_cache
967 if res
!= null then return res
968 res
= self.build_c_name
969 self.c_name_cache
= res
973 # Non cached version of `c_name`
974 protected fun build_c_name
: String is abstract
976 protected var c_name_cache
: nullable String writable = null
978 # Implements a call of the runtime_function
979 # May inline the body or generate a C function call
980 fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
982 # Generate the code for the RuntimeFunction
983 # Warning: compile more than once compilation makes CC unhappy
984 fun compile_to_c
(compiler
: COMPILER) is abstract
987 # A runtime variable hold a runtime value in C.
988 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
990 # 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.
991 class RuntimeVariable
992 # The name of the variable in the C code
995 # The static type of the variable (as declard in C)
998 # The current casted type of the variable (as known in Nit)
999 var mcasttype
: MType writable
1001 # If the variable exaclty a mcasttype?
1002 # false (usual value) means that the variable is a mcasttype or a subtype.
1003 var is_exact
: Bool writable = false
1005 init(name
: String, mtype
: MType, mcasttype
: MType)
1009 self.mcasttype
= mcasttype
1010 assert not mtype
.need_anchor
1011 assert not mcasttype
.need_anchor
1014 redef fun to_s
do return name
1019 if self.is_exact
then
1020 exact_str
= " exact"
1025 if self.mtype
== self.mcasttype
then
1026 type_str
= "{mtype}{exact_str}"
1028 type_str
= "{mtype}({mcasttype}{exact_str})"
1030 return "<{name}:{type_str}>"
1034 # A frame correspond to a visited property in a GlobalCompilerVisitor
1037 type VISITOR: AbstractCompilerVisitor
1039 # The associated visitor
1040 var visitor
: VISITOR
1042 # The executed property.
1043 # A Method in case of a call, an attribute in case of a default initialization.
1044 var mpropdef
: MPropDef
1046 # The static type of the receiver
1047 var receiver
: MClassType
1049 # Arguments of the method (the first is the receiver)
1050 var arguments
: Array[RuntimeVariable]
1052 # The runtime_variable associated to the return (in a function)
1053 var returnvar
: nullable RuntimeVariable writable = null
1055 # The label at the end of the property
1056 var returnlabel
: nullable String writable = null
1059 # An extern C file to compile
1061 # The filename of the file
1062 var filename
: String
1063 # Additionnal specific CC compiler -c flags
1068 # Mangle a string to be a unique valid C identifier
1069 fun to_cmangle
: String
1071 var res
= new Buffer
1072 var underscore
= false
1074 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
1080 res
.append
('_'.ascii
.to_s
)
1083 if c
>= '0' and c
<= '9' then
1086 else if c
== '_' then
1091 res
.append
(c
.ascii
.to_s
)
1099 # Escape " \ ' and non printable characters for literal C strings or characters
1100 fun escape_to_c
: String
1106 else if c
== '\0' then
1108 else if c
== '"' then
1110 else if c == '\'' then
1112 else if c == '\\
' then
1114 else if c.ascii < 32 then
1115 b.append("\\{c.ascii.to_base(8, false)}")
1125 # Return the C type associated to a given Nit static type
1126 fun ctype: String do return "val*"
1128 fun ctypename: String do return "val"
1130 # Return the name of the C structure associated to a Nit live type
1131 fun c_name: String is abstract
1132 protected var c_name_cache: nullable String protected writable
1135 redef class MClassType
1138 var res = self.c_name_cache
1139 if res != null then return res
1140 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
1141 self.c_name_cache = res
1145 redef fun ctype: String
1147 if mclass.name == "Int" then
1149 else if mclass.name == "Bool" then
1151 else if mclass.name == "Char" then
1153 else if mclass.name == "Float" then
1155 else if mclass.name == "NativeString" then
1157 else if mclass.name == "NativeArray" then
1159 else if mclass.kind == extern_kind then
1166 redef fun ctypename: String
1168 if mclass.name == "Int" then
1170 else if mclass.name == "Bool" then
1172 else if mclass.name == "Char" then
1174 else if mclass.name == "Float" then
1176 else if mclass.name == "NativeString" then
1178 else if mclass.name == "NativeArray" then
1179 #return "{self.arguments.first.ctype}*"
1181 else if mclass.kind == extern_kind then
1189 redef class MGenericType
1192 var res = self.c_name_cache
1193 if res != null then return res
1195 for t in self.arguments do
1196 res = res + t.c_name
1198 self.c_name_cache = res
1203 redef class MParameterType
1206 var res = self.c_name_cache
1207 if res != null then return res
1208 res = "{self.mclass.c_name}_FT{self.rank}"
1209 self.c_name_cache = res
1214 redef class MVirtualType
1217 var res = self.c_name_cache
1218 if res != null then return res
1219 res = "{self.mproperty.intro.mclassdef.mclass.c_name}_VT{self.mproperty.name}"
1220 self.c_name_cache = res
1225 redef class MNullableType
1228 var res = self.c_name_cache
1229 if res != null then return res
1230 res = "nullable_{self.mtype.c_name}"
1231 self.c_name_cache = res
1237 # Return the name of the C structure associated to a Nit class
1238 fun c_name: String do
1239 var res = self.c_name_cache
1240 if res != null then return res
1241 res = "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1242 self.c_name_cache = res
1245 private var c_name_cache: nullable String
1248 redef class MProperty
1249 fun c_name: String do
1250 var res = self.c_name_cache
1251 if res != null then return res
1252 res = "{self.intro.c_name}"
1253 self.c_name_cache = res
1256 private var c_name_cache: nullable String
1259 redef class MPropDef
1260 type VISITOR: AbstractCompilerVisitor
1262 private var c_name_cache: nullable String
1264 # The mangled name associated to the property
1267 var res = self.c_name_cache
1268 if res != null then return res
1269 res = "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1270 self.c_name_cache = res
1275 redef class MMethodDef
1276 # Can the body be inlined?
1277 fun can_inline(v: VISITOR): Bool
1279 var modelbuilder = v.compiler.modelbuilder
1280 if modelbuilder.mpropdef2npropdef.has_key(self) then
1281 var npropdef = modelbuilder.mpropdef2npropdef[self]
1282 return npropdef.can_inline
1283 else if self.mproperty.name == "init" then
1284 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1291 # Inline the body in another visitor
1292 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1294 var modelbuilder = v.compiler.modelbuilder
1295 if modelbuilder.mpropdef2npropdef.has_key(self) then
1296 var npropdef = modelbuilder.mpropdef2npropdef[self]
1297 var oldnode = v.current_node
1298 v.current_node = npropdef
1299 self.compile_parameter_check(v, arguments)
1300 npropdef.compile_to_c(v, self, arguments)
1301 v.current_node = oldnode
1302 else if self.mproperty.name == "init" then
1303 var nclassdef = modelbuilder.mclassdef2nclassdef[self.mclassdef]
1304 var oldnode = v.current_node
1305 v.current_node = nclassdef
1306 self.compile_parameter_check(v, arguments)
1307 nclassdef.compile_to_c(v, self, arguments)
1308 v.current_node = oldnode
1315 # Generate type checks in the C code to check covariant parameters
1316 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1318 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1320 for i in [0..msignature.arity[ do
1321 # skip test for vararg since the array is instantiated with the correct polymorphic type
1322 if msignature.vararg_rank == i then continue
1324 # skip if the cast is not required
1325 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1326 if not origmtype.need_anchor then continue
1328 # get the parameter type
1329 var mtype = self.msignature.mparameters[i].mtype
1332 # note that v decides if and how to implements the cast
1333 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1334 var cond = v.type_test(arguments[i+1], mtype, "covariance")
1335 v.add("if (!{cond}) \{")
1336 v.add_abort("Cast failed")
1344 redef class APropdef
1345 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1347 v.add("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1348 debug("Not yet implemented")
1351 fun can_inline: Bool do return true
1354 redef class AConcreteMethPropdef
1355 redef fun compile_to_c(v, mpropdef, arguments)
1357 for i in [0..mpropdef.msignature.arity[ do
1358 var variable = self.n_signature.n_params[i].variable.as(not null)
1359 v.assign(v.variable(variable), arguments[i+1])
1361 # Call the implicit super-init
1362 var auto_super_inits = self.auto_super_inits
1363 if auto_super_inits != null then
1364 var selfarg = [arguments.first]
1365 for auto_super_init in auto_super_inits do
1366 if auto_super_init.intro.msignature.arity == 0 then
1367 v.send(auto_super_init, selfarg)
1369 v.send(auto_super_init, arguments)
1373 v.stmt(self.n_block)
1376 redef fun can_inline
1378 if self.auto_super_inits != null then return false
1379 var nblock = self.n_block
1380 if nblock == null then return true
1381 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1382 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1387 redef class AInternMethPropdef
1388 redef fun compile_to_c(v, mpropdef, arguments)
1390 var pname = mpropdef.mproperty.name
1391 var cname = mpropdef.mclassdef.mclass.name
1392 var ret = mpropdef.msignature.return_mtype
1394 ret = v.resolve_for(ret, arguments.first)
1396 if pname != "==" and pname != "!=" then
1397 v.adapt_signature(mpropdef, arguments)
1399 if cname == "Int" then
1400 if pname == "output" then
1401 v.add("printf(\"%ld\\n\", {arguments.first});")
1403 else if pname == "object_id" then
1404 v.ret(arguments.first)
1406 else if pname == "+" then
1407 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1409 else if pname == "-" then
1410 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1412 else if pname == "unary -" then
1413 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1415 else if pname == "succ" then
1416 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1418 else if pname == "prec" then
1419 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1421 else if pname == "*" then
1422 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1424 else if pname == "/" then
1425 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1427 else if pname == "%" then
1428 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1430 else if pname == "lshift" then
1431 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1433 else if pname == "rshift" then
1434 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1436 else if pname == "==" then
1437 v.ret(v.equal_test(arguments[0], arguments[1]))
1439 else if pname == "!=" then
1440 var res = v.equal_test(arguments[0], arguments[1])
1441 v.ret(v.new_expr("!{res}", ret.as(not null)))
1443 else if pname == "<" then
1444 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1446 else if pname == ">" then
1447 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1449 else if pname == "<=" then
1450 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1452 else if pname == ">=" then
1453 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1455 else if pname == "to_f" then
1456 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
1458 else if pname == "ascii" then
1459 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1462 else if cname == "Char" then
1463 if pname == "output" then
1464 v.add("printf(\"%c\", {arguments.first});")
1466 else if pname == "object_id" then
1467 v.ret(arguments.first)
1469 else if pname == "+" then
1470 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1472 else if pname == "-" then
1473 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1475 else if pname == "==" then
1476 v.ret(v.equal_test(arguments[0], arguments[1]))
1478 else if pname == "!=" then
1479 var res = v.equal_test(arguments[0], arguments[1])
1480 v.ret(v.new_expr("!{res}", ret.as(not null)))
1482 else if pname == "succ" then
1483 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1485 else if pname == "prec" then
1486 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1488 else if pname == "<" then
1489 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1491 else if pname == ">" then
1492 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1494 else if pname == "<=" then
1495 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1497 else if pname == ">=" then
1498 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1500 else if pname == "to_i" then
1501 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
1503 else if pname == "ascii" then
1504 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
1507 else if cname == "Bool" then
1508 if pname == "output" then
1509 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
1511 else if pname == "object_id" then
1512 v.ret(arguments.first)
1514 else if pname == "==" then
1515 v.ret(v.equal_test(arguments[0], arguments[1]))
1517 else if pname == "!=" then
1518 var res = v.equal_test(arguments[0], arguments[1])
1519 v.ret(v.new_expr("!{res}", ret.as(not null)))
1522 else if cname == "Float" then
1523 if pname == "output" then
1524 v.add("printf(\"%f\\n\", {arguments.first});")
1526 else if pname == "object_id" then
1527 v.ret(v.new_expr("(double){arguments.first}", ret.as(not null)))
1529 else if pname == "+" then
1530 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1532 else if pname == "-" then
1533 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1535 else if pname == "unary -" then
1536 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1538 else if pname == "succ" then
1539 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1541 else if pname == "prec" then
1542 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1544 else if pname == "*" then
1545 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1547 else if pname == "/" then
1548 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1550 else if pname == "==" then
1551 v.ret(v.equal_test(arguments[0], arguments[1]))
1553 else if pname == "!=" then
1554 var res = v.equal_test(arguments[0], arguments[1])
1555 v.ret(v.new_expr("!{res}", ret.as(not null)))
1557 else if pname == "<" then
1558 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1560 else if pname == ">" then
1561 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1563 else if pname == "<=" then
1564 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1566 else if pname == ">=" then
1567 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1569 else if pname == "to_i" then
1570 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
1573 else if cname == "Char" then
1574 if pname == "output" then
1575 v.add("printf(\"%c\", {arguments.first});")
1577 else if pname == "object_id" then
1578 v.ret(arguments.first)
1580 else if pname == "==" then
1581 v.ret(v.equal_test(arguments[0], arguments[1]))
1583 else if pname == "!=" then
1584 var res = v.equal_test(arguments[0], arguments[1])
1585 v.ret(v.new_expr("!{res}", ret.as(not null)))
1587 else if pname == "ascii" then
1588 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1591 else if cname == "NativeString" then
1592 if pname == "[]" then
1593 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
1595 else if pname == "[]=" then
1596 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1598 else if pname == "copy_to" then
1599 v.add("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1601 else if pname == "atoi" then
1602 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
1605 else if cname == "NativeArray" then
1606 v.native_array_def(pname, ret, arguments)
1609 if pname == "exit" then
1610 v.add("exit({arguments[1]});")
1612 else if pname == "sys" then
1613 v.ret(v.new_expr("glob_sys", ret.as(not null)))
1615 else if pname == "calloc_string" then
1616 v.ret(v.new_expr("(char*)nit_alloc({arguments[1]})", ret.as(not null)))
1618 else if pname == "calloc_array" then
1619 v.calloc_array(ret.as(not null), arguments)
1621 else if pname == "object_id" then
1622 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
1624 else if pname == "is_same_type" then
1625 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
1627 else if pname == "output_class_name" then
1628 var nat = v.class_name_string(arguments.first)
1629 v.add("printf(\"%s\\n\", {nat});")
1631 else if pname == "native_class_name" then
1632 var nat = v.class_name_string(arguments.first)
1633 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
1635 else if pname == "force_garbage_collection" then
1636 v.add("nit_gcollect();")
1638 else if pname == "native_argc" then
1639 v.ret(v.new_expr("glob_argc", ret.as(not null)))
1641 else if pname == "native_argv" then
1642 v.ret(v.new_expr("glob_argv[{arguments[1]}]", ret.as(not null)))
1645 v.add("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at {location.to_s}\\n\");")
1646 debug("Not implemented {mpropdef}")
1650 redef class AExternMethPropdef
1651 redef fun compile_to_c(v, mpropdef, arguments)
1654 var nextern = self.n_extern
1655 if nextern == null then
1656 v.add("fprintf(stderr, \"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1660 externname = nextern.text.substring(1, nextern.text.length-2)
1661 if location.file != null then
1662 var file = location.file.filename
1665 var res: nullable RuntimeVariable = null
1666 var ret = mpropdef.msignature.return_mtype
1668 ret = v.resolve_for(ret, arguments.first)
1669 res = v.new_var(ret)
1671 v.adapt_signature(mpropdef, arguments)
1674 v.add("{externname}({arguments.join(", ")});")
1676 v.add("{res} = {externname}({arguments.join(", ")});")
1682 redef class AExternInitPropdef
1683 redef fun compile_to_c(v, mpropdef, arguments)
1686 var nextern = self.n_extern
1687 if nextern == null then
1688 v.add("printf(\"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1692 externname = nextern.text.substring(1, nextern.text.length-2)
1693 if location.file != null then
1694 var file = location.file.filename
1697 v.adapt_signature(mpropdef, arguments)
1698 var ret = arguments.first.mtype
1699 var res = v.new_var(ret)
1703 v.add("{res} = {externname}({arguments.join(", ")});")
1708 redef class AAttrPropdef
1709 redef fun compile_to_c(v, mpropdef, arguments)
1711 if arguments.length == 1 then
1712 var res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
1713 v.assign(v.frame.returnvar.as(not null), res)
1715 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
1719 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1721 var nexpr = self.n_expr
1722 if nexpr != null then
1723 var oldnode = v.current_node
1724 v.current_node = self
1725 var old_frame = v.frame
1726 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1728 var value = v.expr(nexpr, self.mpropdef.static_mtype)
1729 v.write_attribute(self.mpropdef.mproperty, recv, value)
1731 v.current_node = oldnode
1735 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1737 var nexpr = self.n_expr
1738 if nexpr != null then return
1740 var oldnode = v.current_node
1741 v.current_node = self
1742 var old_frame = v.frame
1743 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1745 # Force read to check the initialization
1746 v.read_attribute(self.mpropdef.mproperty, recv)
1748 v.current_node = oldnode
1752 redef class AClassdef
1753 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1755 if mpropdef == self.mfree_init then
1756 var super_inits = self.super_inits
1757 if super_inits != null then
1758 assert arguments.length == 1
1759 for su in super_inits do
1760 v.send(su, arguments)
1764 var recv = arguments.first
1766 # Collect undefined attributes
1767 for npropdef in self.n_propdefs do
1768 if npropdef isa AAttrPropdef and npropdef.n_expr == null then
1769 v.write_attribute(npropdef.mpropdef.mproperty, recv, arguments[i])
1779 redef class ADeferredMethPropdef
1780 redef fun compile_to_c(v, mpropdef, arguments) do v.add_abort("Deferred method called")
1781 redef fun can_inline do return true
1785 # Try to compile self as an expression
1786 # Do not call this method directly, use `v.expr' instead
1787 private fun expr
(v
: AbstractCompilerVisitor): nullable RuntimeVariable
1789 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
1790 var mtype
= self.mtype
1791 if mtype
== null then
1794 var res
= v
.new_var
(mtype
)
1795 v
.add
("/* {res} = NOT YET {class_name} */")
1800 # Try to compile self as a statement
1801 # Do not call this method directly, use `v.stmt' instead
1802 private fun stmt
(v
: AbstractCompilerVisitor)
1805 if res
!= null then v
.add
("{res};")
1809 redef class ABlockExpr
1812 for e
in self.n_expr
do v
.stmt
(e
)
1816 var last
= self.n_expr
.last
1817 for e
in self.n_expr
do
1818 if e
== last
then break
1821 return v
.expr
(last
, null)
1825 redef class AVardeclExpr
1828 var variable
= self.variable
.as(not null)
1829 var ne
= self.n_expr
1831 var i
= v
.expr
(ne
, variable
.declared_type
)
1832 v
.assign
(v
.variable
(variable
), i
)
1837 redef class AVarExpr
1840 var res
= v
.variable
(self.variable
.as(not null))
1841 var mtype
= self.mtype
.as(not null)
1842 return v
.autoadapt
(res
, mtype
)
1846 redef class AVarAssignExpr
1849 var variable
= self.variable
.as(not null)
1850 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1851 v
.assign
(v
.variable
(variable
), i
)
1855 redef class AVarReassignExpr
1858 var variable
= self.variable
.as(not null)
1859 var vari
= v
.variable
(variable
)
1860 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1861 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [vari
, value
])
1863 v
.assign
(v
.variable
(variable
), res
)
1867 redef class ASelfExpr
1868 redef fun expr
(v
) do return v
.frame
.arguments
.first
1871 redef class AContinueExpr
1872 redef fun stmt
(v
) do v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
1875 redef class ABreakExpr
1876 redef fun stmt
(v
) do v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
1879 redef class AReturnExpr
1882 var nexpr
= self.n_expr
1883 if nexpr
!= null then
1884 var returnvar
= v
.frame
.returnvar
.as(not null)
1885 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
1886 v
.assign
(returnvar
, i
)
1888 v
.add
("goto {v.frame.returnlabel.as(not null)};")
1892 redef class AAbortExpr
1893 redef fun stmt
(v
) do v
.add_abort
("Aborted")
1899 var cond
= v
.expr_bool
(self.n_expr
)
1900 v
.add
("if ({cond})\{")
1908 redef class AIfexprExpr
1911 var res
= v
.new_var
(self.mtype
.as(not null))
1912 var cond
= v
.expr_bool
(self.n_expr
)
1913 v
.add
("if ({cond})\{")
1914 v
.assign
(res
, v
.expr
(self.n_then
, null))
1916 v
.assign
(res
, v
.expr
(self.n_else
, null))
1925 v
.stmt
(self.n_block
)
1926 var escapemark
= self.escapemark
1927 if escapemark
!= null then
1928 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1933 redef class AWhileExpr
1937 var cond
= v
.expr_bool
(self.n_expr
)
1938 v
.add
("if (!{cond}) break;")
1939 v
.stmt
(self.n_block
)
1940 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1942 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1946 redef class ALoopExpr
1950 v
.stmt
(self.n_block
)
1951 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1953 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1957 redef class AForExpr
1960 # Shortcut on explicit range
1961 # Avoid the instantiation of the range and the iterator
1962 var nexpr
= self.n_expr
1963 if self.variables
.length
== 1 and nexpr
isa AOrangeExpr and not v
.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_range
.value
then
1964 var from
= v
.expr
(nexpr
.n_expr
, null)
1965 var to
= v
.expr
(nexpr
.n_expr2
, null)
1966 var variable
= v
.variable
(variables
.first
)
1968 v
.assign
(variable
, from
)
1969 v
.add
("for(;;) \{ /* shortcut range */")
1971 var ok
= v
.send
(v
.get_property
("<", variable
.mtype
), [variable
, to
])
1973 v
.add
("if(!{ok}) break;")
1975 v
.stmt
(self.n_block
)
1977 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1978 var succ
= v
.send
(v
.get_property
("succ", variable
.mtype
), [variable
])
1980 v
.assign
(variable
, succ
)
1982 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1986 var cl
= v
.expr
(self.n_expr
, null)
1987 var it_meth
= self.method_iterator
1988 assert it_meth
!= null
1989 var it
= v
.send
(it_meth
, [cl
])
1992 var isok_meth
= self.method_is_ok
1993 assert isok_meth
!= null
1994 var ok
= v
.send
(isok_meth
, [it
])
1996 v
.add
("if(!{ok}) break;")
1997 if self.variables
.length
== 1 then
1998 var item_meth
= self.method_item
1999 assert item_meth
!= null
2000 var i
= v
.send
(item_meth
, [it
])
2002 v
.assign
(v
.variable
(variables
.first
), i
)
2003 else if self.variables
.length
== 2 then
2004 var key_meth
= self.method_key
2005 assert key_meth
!= null
2006 var i
= v
.send
(key_meth
, [it
])
2008 v
.assign
(v
.variable
(variables
[0]), i
)
2009 var item_meth
= self.method_item
2010 assert item_meth
!= null
2011 i
= v
.send
(item_meth
, [it
])
2013 v
.assign
(v
.variable
(variables
[1]), i
)
2017 v
.stmt
(self.n_block
)
2018 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2019 var next_meth
= self.method_next
2020 assert next_meth
!= null
2021 v
.send
(next_meth
, [it
])
2023 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2027 redef class AAssertExpr
2030 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
2032 var cond
= v
.expr_bool
(self.n_expr
)
2033 v
.add
("if (!{cond}) \{")
2037 v
.add_abort
("Assert '{nid.text}' failed")
2039 v
.add_abort
("Assert failed")
2048 var res
= v
.new_var
(self.mtype
.as(not null))
2049 var i1
= v
.expr_bool
(self.n_expr
)
2050 v
.add
("if ({i1}) \{")
2053 var i2
= v
.expr_bool
(self.n_expr2
)
2054 v
.add
("{res} = {i2};")
2060 redef class AAndExpr
2063 var res
= v
.new_var
(self.mtype
.as(not null))
2064 var i1
= v
.expr_bool
(self.n_expr
)
2065 v
.add
("if (!{i1}) \{")
2068 var i2
= v
.expr_bool
(self.n_expr2
)
2069 v
.add
("{res} = {i2};")
2075 redef class ANotExpr
2078 var cond
= v
.expr_bool
(self.n_expr
)
2079 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2083 redef class AOrElseExpr
2086 var res
= v
.new_var
(self.mtype
.as(not null))
2087 var i1
= v
.expr
(self.n_expr
, null)
2088 v
.add
("if ({i1}!=NULL) \{")
2091 var i2
= v
.expr
(self.n_expr2
, null)
2101 var value1
= v
.expr
(self.n_expr
, null)
2102 var value2
= v
.expr
(self.n_expr2
, null)
2103 return v
.equal_test
(value1
, value2
)
2107 redef class AIntExpr
2108 redef fun expr
(v
) do return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2111 redef class AFloatExpr
2112 redef fun expr
(v
) do return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2115 redef class ACharExpr
2116 redef fun expr
(v
) do return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2119 redef class AArrayExpr
2122 var mtype
= self.mtype
.as(MClassType).arguments
.first
2123 var array
= new Array[RuntimeVariable]
2124 for nexpr
in self.n_exprs
.n_exprs
do
2125 var i
= v
.expr
(nexpr
, mtype
)
2128 return v
.array_instance
(array
, mtype
)
2132 redef class AStringFormExpr
2133 redef fun expr
(v
) do return v
.string_instance
(self.value
.as(not null))
2136 redef class ASuperstringExpr
2139 var array
= new Array[RuntimeVariable]
2140 for ne
in self.n_exprs
do
2141 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2142 var i
= v
.expr
(ne
, null)
2145 var a
= v
.array_instance
(array
, v
.object_type
)
2146 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2151 redef class ACrangeExpr
2154 var i1
= v
.expr
(self.n_expr
, null)
2155 var i2
= v
.expr
(self.n_expr2
, null)
2156 var mtype
= self.mtype
.as(MClassType)
2157 var res
= v
.init_instance
(mtype
)
2158 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2159 v
.check_init_instance
(res
, mtype
)
2164 redef class AOrangeExpr
2167 var i1
= v
.expr
(self.n_expr
, null)
2168 var i2
= v
.expr
(self.n_expr2
, null)
2169 var mtype
= self.mtype
.as(MClassType)
2170 var res
= v
.init_instance
(mtype
)
2171 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2172 v
.check_init_instance
(res
, mtype
)
2177 redef class ATrueExpr
2178 redef fun expr
(v
) do return v
.new_expr
("1", self.mtype
.as(not null))
2181 redef class AFalseExpr
2182 redef fun expr
(v
) do return v
.new_expr
("0", self.mtype
.as(not null))
2185 redef class ANullExpr
2186 redef fun expr
(v
) do return v
.new_expr
("NULL", self.mtype
.as(not null))
2189 redef class AIsaExpr
2192 var i
= v
.expr
(self.n_expr
, null)
2193 return v
.type_test
(i
, self.cast_type
.as(not null), "isa")
2197 redef class AAsCastExpr
2200 var i
= v
.expr
(self.n_expr
, null)
2201 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2203 var cond
= v
.type_test
(i
, self.mtype
.as(not null), "as")
2204 v
.add
("if (!{cond}) \{")
2205 v
.add_abort
("Cast failed")
2211 redef class AAsNotnullExpr
2214 var i
= v
.expr
(self.n_expr
, null)
2215 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2217 v
.add
("if ({i} == NULL) \{")
2218 v
.add_abort
("Cast failed")
2224 redef class AParExpr
2225 redef fun expr
(v
) do return v
.expr
(self.n_expr
, null)
2228 redef class AOnceExpr
2231 var mtype
= self.mtype
.as(not null)
2232 var name
= v
.get_name
("varonce")
2233 var guard
= v
.get_name
(name
+ "_guard")
2234 v
.add_decl
("static {mtype.ctype} {name};")
2235 v
.add_decl
("static int {guard};")
2236 var res
= v
.new_var
(mtype
)
2237 v
.add
("if ({guard}) \{")
2238 v
.add
("{res} = {name};")
2240 var i
= v
.expr
(self.n_expr
, mtype
)
2241 v
.add
("{res} = {i};")
2242 v
.add
("{name} = {res};")
2243 v
.add
("{guard} = 1;")
2249 redef class ASendExpr
2252 var recv
= v
.expr
(self.n_expr
, null)
2254 for a
in self.raw_arguments
.as(not null) do
2255 args
.add
(v
.expr
(a
, null))
2257 return v
.compile_callsite
(self.callsite
.as(not null), args
)
2261 redef class ASendReassignFormExpr
2264 var recv
= v
.expr
(self.n_expr
, null)
2266 for a
in self.raw_arguments
.as(not null) do
2267 args
.add
(v
.expr
(a
, null))
2269 var value
= v
.expr
(self.n_value
, null)
2271 var left
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2274 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [left
, value
])
2278 v
.compile_callsite
(self.write_callsite
.as(not null), args
)
2282 redef class ASuperExpr
2285 var recv
= v
.frame
.arguments
.first
2287 for a
in self.n_args
.n_exprs
do
2288 args
.add
(v
.expr
(a
, null))
2290 if args
.length
== 1 then
2291 args
= v
.frame
.arguments
2294 var mproperty
= self.mproperty
2295 if mproperty
!= null then
2296 if mproperty
.intro
.msignature
.arity
== 0 then
2300 var res
= v
.send
(mproperty
, args
)
2304 # stantard call-next-method
2305 return v
.supercall
(v
.frame
.mpropdef
.as(MMethodDef), recv
.mtype
.as(MClassType), args
)
2309 redef class ANewExpr
2312 var mtype
= self.mtype
.as(MClassType)
2314 var ctype
= mtype
.ctype
2315 if ctype
== "val*" then
2316 recv
= v
.init_instance
(mtype
)
2317 else if ctype
== "void*" then
2318 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2320 debug
("cannot new {mtype}")
2324 for a
in self.n_args
.n_exprs
do
2325 args
.add
(v
.expr
(a
, null))
2327 var res2
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2328 if res2
!= null then
2329 #self.debug("got {res2} from {mproperty}. drop {recv}")
2332 v
.check_init_instance
(recv
, mtype
)
2337 redef class AAttrExpr
2340 var recv
= v
.expr
(self.n_expr
, null)
2341 var mproperty
= self.mproperty
.as(not null)
2342 return v
.read_attribute
(mproperty
, recv
)
2346 redef class AAttrAssignExpr
2349 var recv
= v
.expr
(self.n_expr
, null)
2350 var i
= v
.expr
(self.n_value
, null)
2351 var mproperty
= self.mproperty
.as(not null)
2352 v
.write_attribute
(mproperty
, recv
, i
)
2356 redef class AAttrReassignExpr
2359 var recv
= v
.expr
(self.n_expr
, null)
2360 var value
= v
.expr
(self.n_value
, null)
2361 var mproperty
= self.mproperty
.as(not null)
2362 var attr
= v
.read_attribute
(mproperty
, recv
)
2363 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [attr
, value
])
2365 v
.write_attribute
(mproperty
, recv
, res
)
2369 redef class AIssetAttrExpr
2372 var recv
= v
.expr
(self.n_expr
, null)
2373 var mproperty
= self.mproperty
.as(not null)
2374 return v
.isset_attribute
(mproperty
, recv
)
2378 redef class ADebugTypeExpr
2387 redef class Array[E
]
2388 # Return a new Array with the elements only contened in 'self' and not in 'o'
2389 fun -(o
: Array[E
]): Array[E
] do
2390 var res
= new Array[E
]
2391 for e
in self do if not o
.has
(e
) then res
.add
(e
)
2397 # All 'mproperties' associated to all 'mclassdefs' of `mclass`
2398 fun properties
(mclass
: MClass): Set[MProperty] do
2399 if not self.properties_cache
.has_key
(mclass
) then
2400 var properties
= new HashSet[MProperty]
2401 var parents
= new Array[MClass]
2402 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2403 parents
.add_all
(mclass
.in_hierarchy
(self).direct_greaters
)
2405 for parent
in parents
do
2406 properties
.add_all
(self.properties
(parent
))
2408 for mclassdef
in mclass
.mclassdefs
do
2409 for mprop
in mclassdef
.intro_mproperties
do
2410 properties
.add
(mprop
)
2413 self.properties_cache
[mclass
] = properties
2415 return properties_cache
[mclass
]
2417 private var properties_cache
: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]