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_make_flags
: OptionString = new OptionString("Additional options to make", "--make-flags")
33 var opt_hardening
: OptionBool = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
35 var opt_no_shortcut_range
: OptionBool = new OptionBool("Always insantiate a range and its iterator on 'for' loops", "--no-shortcut-range")
36 # --no-check-covariance
37 var opt_no_check_covariance
: OptionBool = new OptionBool("Disable type tests of covariant parameters (dangerous)", "--no-check-covariance")
38 # --no-check-initialization
39 var opt_no_check_initialization
: OptionBool = new OptionBool("Disable isset tests at the end of constructors (dangerous)", "--no-check-initialization")
41 var opt_no_check_assert
: OptionBool = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
43 var opt_no_check_autocast
: OptionBool = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
45 var opt_no_check_other
: OptionBool = new OptionBool("Disable implicit tests: unset attribute, null receiver (dangerous)", "--no-check-other")
46 # --typing-test-metrics
47 var opt_typing_test_metrics
: OptionBool = new OptionBool("Enable static and dynamic count of all type tests", "--typing-test-metrics")
52 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_make_flags
, self.opt_hardening
, self.opt_no_shortcut_range
)
53 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
)
54 self.option_context
.add_option
(self.opt_typing_test_metrics
)
58 redef class ModelBuilder
59 protected fun write_and_make
(compiler
: AbstractCompiler)
61 var mainmodule
= compiler
.mainmodule
63 # Generate the .h and .c files
64 # A single C file regroups many compiled rumtime functions
65 # 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
70 var outname
= self.toolcontext
.opt_output
.value
71 if outname
== null then
72 outname
= "{mainmodule.name}.bin"
75 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
76 var h
= new OFStream.open
(hfilename
)
77 for l
in compiler
.header
.decl_lines
do
83 var cfiles
= new Array[String]
85 for f
in compiler
.files
do
87 var file
: nullable OFStream = null
89 for vis
in f
.writers
do
90 count
+= vis
.lines
.length
91 if file
== null or count
> 10000 then
93 if file
!= null then file
.close
94 var cfilename
= ".nit_compile/{f.name}.{i}.c"
95 self.toolcontext
.info
("new C source files to compile: {cfilename}", 3)
97 file
= new OFStream.open
(cfilename
)
98 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
99 count
= vis
.lines
.length
101 if vis
!= compiler
.header
then
102 for l
in vis
.decl_lines
do
107 for l
in vis
.lines
do
112 if file
!= null then file
.close
115 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
117 # Generate the Makefile
119 var makename
= ".nit_compile/{mainmodule.name}.mk"
120 var makefile
= new OFStream.open
(makename
)
122 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
123 makefile
.write
("all: {outname}\n\n")
125 var ofiles
= new Array[String]
126 # Compile each generated file
128 var o
= f
.strip_extension
(".c") + ".o"
129 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
132 # Compile each required extern body into a specific .o
133 for f
in compiler
.extern_bodies
do
134 var basename
= f
.basename
(".c")
135 var o
= ".nit_compile/{basename}.extern.o"
136 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
140 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
142 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
144 self.toolcontext
.info
("Generated makefile: {makename}", 2)
147 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
149 # Execute the Makefile
151 if self.toolcontext
.opt_no_cc
.value
then return
154 self.toolcontext
.info
("*** COMPILING C ***", 1)
155 var makeflags
= self.toolcontext
.opt_make_flags
.value
156 if makeflags
== null then makeflags
= ""
157 self.toolcontext
.info
("make -B -f {makename} -j 4 {makeflags}", 2)
160 if self.toolcontext
.verbose_level
>= 3 then
161 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1")
163 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
166 toolcontext
.error
(null, "make failed! Error code: {res}.")
170 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
174 # Singleton that store the knowledge about the compilation process
175 abstract class AbstractCompiler
176 type VISITOR: AbstractCompilerVisitor
178 # The main module of the program
179 var mainmodule
: MModule protected writable
181 # The modeulbuilder used to know the model and the AST
182 var modelbuilder
: ModelBuilder protected writable
184 # Is hardening asked? (see --hardening)
185 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
187 init(mainmodule
: MModule, modelbuilder
: ModelBuilder)
189 self.mainmodule
= mainmodule
190 self.modelbuilder
= modelbuilder
191 var file
= new_file
(mainmodule
.name
)
192 self.header
= new CodeWriter(file
)
195 # Force the creation of a new file
196 # The point is to avoid contamination between must-be-compiled-separately files
197 fun new_file
(name
: String): CodeFile
199 var f
= new CodeFile(name
)
204 # The list of all associated files
205 # Used to generate .c files
206 var files
: List[CodeFile] = new List[CodeFile]
208 # Initialize a visitor specific for a compiler engine
209 fun new_visitor
: VISITOR is abstract
211 # Where global declaration are stored (the main .h)
213 # FIXME: should not have a global .h since it does not help recompilations
214 var header
: CodeWriter writable
217 # This method call compile_header_strucs method that has to be refined
218 fun compile_header
do
220 self.header
.add_decl
("#include <stdlib.h>")
221 self.header
.add_decl
("#include <stdio.h>")
222 self.header
.add_decl
("#include <string.h>")
223 self.header
.add_decl
("#ifndef NOBOEHM")
224 self.header
.add_decl
("#include <gc/gc.h>")
225 self.header
.add_decl
("#ifdef NOBOEHM_ATOMIC")
226 self.header
.add_decl
("#undef GC_MALLOC_ATOMIC")
227 self.header
.add_decl
("#define GC_MALLOC_ATOMIC(x) GC_MALLOC(x)")
228 self.header
.add_decl
("#endif /*NOBOEHM_ATOMIC*/")
229 self.header
.add_decl
("#else /*NOBOEHM*/")
230 self.header
.add_decl
("#define GC_MALLOC(x) calloc(1, (x))")
231 self.header
.add_decl
("#define GC_MALLOC_ATOMIC(x) calloc(1, (x))")
232 self.header
.add_decl
("#endif /*NOBOEHM*/")
234 compile_header_structs
236 # Global variable used by the legacy native interface
237 self.header
.add_decl
("extern int glob_argc;")
238 self.header
.add_decl
("extern char **glob_argv;")
239 self.header
.add_decl
("extern val *glob_sys;")
242 # Declaration of structures the live Nit types
243 protected fun compile_header_structs
is abstract
245 # Generate the main C function.
247 # * allocate the Sys object if it exists
248 # * call init if is exists
249 # * call main if it exists
250 fun compile_main_function
252 var v
= self.new_visitor
253 v
.add_decl
("int glob_argc;")
254 v
.add_decl
("char **glob_argv;")
255 v
.add_decl
("val *glob_sys;")
257 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
258 for tag
in count_type_test_tags
do
259 v
.add_decl
("long count_type_test_resolved_{tag};")
260 v
.add_decl
("long count_type_test_unresolved_{tag};")
261 v
.add_decl
("long count_type_test_skipped_{tag};")
262 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
263 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
264 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
267 v
.add_decl
("int main(int argc, char** argv) \{")
268 v
.add
("glob_argc = argc; glob_argv = argv;")
269 var main_type
= mainmodule
.sys_type
270 if main_type
!= null then
271 var mainmodule
= v
.compiler
.mainmodule
272 var glob_sys
= v
.init_instance
(main_type
)
273 v
.add
("glob_sys = {glob_sys};")
274 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
275 if main_init
!= null then
276 v
.send
(main_init
, [glob_sys
])
278 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
279 if main_method
!= null then
280 v
.send
(main_method
, [glob_sys
])
284 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
285 v
.add_decl
("long count_type_test_resolved_total = 0;")
286 v
.add_decl
("long count_type_test_unresolved_total = 0;")
287 v
.add_decl
("long count_type_test_skipped_total = 0;")
288 v
.add_decl
("long count_type_test_total_total = 0;")
289 for tag
in count_type_test_tags
do
290 v
.add_decl
("long count_type_test_total_{tag};")
291 v
.add
("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
292 v
.add
("count_type_test_resolved_total += count_type_test_resolved_{tag};")
293 v
.add
("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
294 v
.add
("count_type_test_skipped_total += count_type_test_skipped_{tag};")
295 v
.add
("count_type_test_total_total += count_type_test_total_{tag};")
297 v
.add
("printf(\"# dynamic count_type_test: total %l\\n\");")
298 v
.add
("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\
");")
299 var tags
= count_type_test_tags
.to_a
302 v
.add
("printf(\"{tag}\
");")
303 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
304 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
305 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
306 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\\n\
", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
313 # look for a needed .h and .c file for a given .nit source-file
314 # FIXME: bad API, parameter should be a MModule, not its source-file
315 fun add_extern
(file
: String)
317 file
= file
.strip_extension
(".nit")
318 var tryfile
= file
+ ".nit.h"
319 if tryfile
.file_exists
then
320 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
322 tryfile
= file
+ "_nit.h"
323 if tryfile
.file_exists
then
324 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
326 tryfile
= file
+ ".nit.c"
327 if tryfile
.file_exists
then
328 self.extern_bodies
.add
(tryfile
)
330 tryfile
= file
+ "_nit.c"
331 if tryfile
.file_exists
then
332 self.extern_bodies
.add
(tryfile
)
336 # List of additional .c files required to compile (native interface)
337 var extern_bodies
= new ArraySet[String]
339 # Generate code that check if an instance is correctly initialized
340 fun generate_check_init_instance
(mtype
: MClassType) is abstract
342 # Generate code that initialize the attributes on a new instance
343 fun generate_init_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
345 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
346 self.mainmodule
.linearize_mclassdefs
(cds
)
348 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
349 for npropdef
in n
.n_propdefs
do
350 if npropdef
isa AAttrPropdef then
351 npropdef
.init_expr
(v
, recv
)
357 # Generate code that check if an attribute is correctly initialized
358 fun generate_check_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
360 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
361 self.mainmodule
.linearize_mclassdefs
(cds
)
363 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
364 for npropdef
in n
.n_propdefs
do
365 if npropdef
isa AAttrPropdef then
366 npropdef
.check_expr
(v
, recv
)
374 var count_type_test_tags
: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
375 var count_type_test_resolved
: HashMap[String, Int] = init_count_type_test_tags
376 var count_type_test_unresolved
: HashMap[String, Int] = init_count_type_test_tags
377 var count_type_test_skipped
: HashMap[String, Int] = init_count_type_test_tags
379 protected fun init_count_type_test_tags
: HashMap[String, Int]
381 var res
= new HashMap[String, Int]
382 for tag
in count_type_test_tags
do
388 # Display stats about compilation process
390 # * type tests against resolved types (x isa Collection[Animal])
391 # * type tests against unresolved types (x isa Collection[E])
392 # * type tests skipped
397 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
398 print
"# static count_type_test"
399 print
"\tresolved:\tunresolved\tskipped\ttotal"
400 var count_type_test_total
= init_count_type_test_tags
401 count_type_test_resolved
["total"] = 0
402 count_type_test_unresolved
["total"] = 0
403 count_type_test_skipped
["total"] = 0
404 count_type_test_total
["total"] = 0
405 for tag
in count_type_test_tags
do
406 count_type_test_total
[tag
] = count_type_test_resolved
[tag
] + count_type_test_unresolved
[tag
] + count_type_test_skipped
[tag
]
407 count_type_test_resolved
["total"] += count_type_test_resolved
[tag
]
408 count_type_test_unresolved
["total"] += count_type_test_unresolved
[tag
]
409 count_type_test_skipped
["total"] += count_type_test_skipped
[tag
]
410 count_type_test_total
["total"] += count_type_test_total
[tag
]
412 var count_type_test
= count_type_test_total
["total"]
413 var tags
= count_type_test_tags
.to_a
417 printn
"\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
418 printn
"\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
419 printn
"\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
420 printn
"\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
427 # Avoid division by zero by returning the string "n/a"
428 fun div
(a
,b
:Int):String
430 if b
== 0 then return "n/a"
431 return ((a
*10000/b
).to_f
/ 100.0).to_precision
(2)
435 # A file unit (may be more than one file if
436 # A file unit aim to be autonomous and is made or one or more `CodeWriter`s
439 var writers
= new Array[CodeWriter]
442 # Where to store generated lines
445 var lines
: List[String] = new List[String]
446 var decl_lines
: List[String] = new List[String]
448 # Add a line in the main part of the generated C
449 fun add
(s
: String) do self.lines
.add
(s
)
452 # (used for local or global declaration)
453 fun add_decl
(s
: String) do self.decl_lines
.add
(s
)
458 file
.writers
.add
(self)
462 # A visitor on the AST of property definition that generate the C code.
463 abstract class AbstractCompilerVisitor
465 type COMPILER: AbstractCompiler
467 # The associated compiler
468 var compiler
: COMPILER
470 # The current visited AST node
471 var current_node
: nullable ANode writable = null
474 var frame
: nullable Frame writable
476 # Alias for self.compiler.mainmodule.object_type
477 fun object_type
: MClassType do return self.compiler
.mainmodule
.object_type
479 # Alias for self.compiler.mainmodule.bool_type
480 fun bool_type
: MClassType do return self.compiler
.mainmodule
.bool_type
482 var writer
: CodeWriter
484 init(compiler
: COMPILER)
486 self.compiler
= compiler
487 self.writer
= new CodeWriter(compiler
.files
.last
)
490 # Force to get the primitive class named `name' or abort
491 fun get_class
(name
: String): MClass do return self.compiler
.mainmodule
.get_primitive_class
(name
)
493 # Force to get the primitive property named `name' in the instance `recv' or abort
494 fun get_property
(name
: String, recv
: MType): MMethod
496 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
, self.compiler
.mainmodule
)
499 fun compile_callsite
(callsite
: CallSite, args
: Array[RuntimeVariable]): nullable RuntimeVariable
501 return self.send
(callsite
.mproperty
, args
)
504 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable]) is abstract
506 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable]) is abstract
508 # Transform varargs, in raw arguments, into a single argument of type Array
509 # Note: this method modify the given `args`
510 # If there is no vararg, then `args` is not modified.
511 fun varargize
(mpropdef
: MPropDef, msignature
: MSignature, args
: Array[RuntimeVariable])
513 var recv
= args
.first
514 var vararg_rank
= msignature
.vararg_rank
515 if vararg_rank
>= 0 then
516 assert args
.length
>= msignature
.arity
+ 1 # because of self
518 args
= new Array[RuntimeVariable]
520 args
.add
(rawargs
.first
) # recv
522 for i
in [0..vararg_rank
[ do
523 args
.add
(rawargs
[i
+1])
526 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-msignature
.arity
527 var vararg
= new Array[RuntimeVariable]
528 for i
in [vararg_rank
..vararg_lastrank
] do
529 vararg
.add
(rawargs
[i
+1])
532 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
533 args
.add
(self.vararg_instance
(mpropdef
, recv
, vararg
, elttype
))
535 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
536 args
.add
(rawargs
[i
+1])
539 rawargs
.add_all
(args
)
545 # Anchor a type to the main module and the current receiver
546 fun anchor
(mtype
: MType): MType
548 if not mtype
.need_anchor
then return mtype
549 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
552 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
554 if not mtype
.need_anchor
then return mtype
555 return mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
558 # Unsafely cast a value to a new type
559 # ie the result share the same C variable but my have a different mcasttype
560 # NOTE: if the adaptation is useless then `value' is returned as it.
561 # ENSURE: return.name == value.name
562 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
564 mtype
= self.anchor
(mtype
)
565 var valmtype
= value
.mcasttype
566 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
570 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
571 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
574 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
579 # Generate a super call from a method definition
580 fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
582 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable]) is abstract
584 # Box or unbox a value to another type iff a C type conversion is needed
585 # ENSURE: result.mtype.ctype == mtype.ctype
586 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
588 # Generate a polymorphic subtype test
589 fun type_test
(value
: RuntimeVariable, mtype
: MType, tag
: String): RuntimeVariable is abstract
591 # Generate the code required to dynamically check if 2 objects share the same runtime type
592 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
594 # Generate a Nit "is" for two runtime_variables
595 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
599 # Generate a static call on a method definition
600 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
602 # Generate a polymorphic send for the method `m' and the arguments `args'
603 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
605 # Generate a monomorphic send for the method `m', the type `t' and the arguments `args'
606 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
608 assert t
isa MClassType
609 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
610 return self.call
(propdef
, t
, args
)
613 # Attributes handling
615 # Generate a polymorphic attribute is_set test
616 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
618 # Generate a polymorphic attribute read
619 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
621 # Generate a polymorphic attribute write
622 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable) is abstract
626 # Add a check and an abort for a null reciever if needed
627 fun check_recv_notnull
(recv
: RuntimeVariable)
629 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
631 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
633 self.add
("if ({recv} == NULL) \{")
634 self.add_abort
("Reciever is null")
639 # Generate a check-init-instance
640 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType) is abstract
644 private var names
: HashSet[String] = new HashSet[String]
645 private var last
: Int = 0
647 # Return a new name based on `s' and unique in the visitor
648 fun get_name
(s
: String): String
650 if not self.names
.has
(s
) then
654 var i
= self.last
+ 1
657 if not self.names
.has
(s2
) then
666 # Return an unique and stable identifier associated with an escapemark
667 fun escapemark_name
(e
: nullable EscapeMark): String
670 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
672 if name
== null then name
= "label"
673 name
= get_name
(name
)
674 escapemark_names
[e
] = name
678 private var escapemark_names
= new HashMap[EscapeMark, String]
680 # Return a "const char*" variable associated to the classname of the dynamic type of an object
681 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
682 fun class_name_string
(value
: RuntimeVariable): String is abstract
686 protected var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
688 # Return the local runtime_variable associated to a Nit local variable
689 fun variable
(variable
: Variable): RuntimeVariable
691 if self.variables
.has_key
(variable
) then
692 return self.variables
[variable
]
694 var name
= self.get_name
("var_{variable.name}")
695 var mtype
= variable
.declared_type
.as(not null)
696 mtype
= self.anchor
(mtype
)
697 var res
= new RuntimeVariable(name
, mtype
, mtype
)
698 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
699 self.variables
[variable
] = res
704 # Return a new uninitialized local runtime_variable
705 fun new_var
(mtype
: MType): RuntimeVariable
707 mtype
= self.anchor
(mtype
)
708 var name
= self.get_name
("var")
709 var res
= new RuntimeVariable(name
, mtype
, mtype
)
710 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
714 # Return a new uninitialized named runtime_variable
715 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
717 mtype
= self.anchor
(mtype
)
718 var res
= new RuntimeVariable(name
, mtype
, mtype
)
719 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
723 # Correctly assign a left and a right value
724 # Boxing and unboxing is performed if required
725 fun assign
(left
, right
: RuntimeVariable)
727 right
= self.autobox
(right
, left
.mtype
)
728 self.add
("{left} = {right};")
733 # Generate a alloc-instance + init-attributes
734 fun init_instance
(mtype
: MClassType): RuntimeVariable is abstract
736 # Generate an integer value
737 fun int_instance
(value
: Int): RuntimeVariable
739 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
740 self.add
("{res} = {value};")
744 # Generate a string value
745 fun string_instance
(string
: String): RuntimeVariable
747 var mtype
= self.get_class
("String").mclass_type
748 var name
= self.get_name
("varonce")
749 self.add_decl
("static {mtype.ctype} {name};")
750 var res
= self.new_var
(mtype
)
751 self.add
("if ({name}) \{")
752 self.add
("{res} = {name};")
753 self.add
("\} else \{")
754 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
755 self.add
("{nat} = \"{string.escape_to_c}\
";")
756 var res2
= self.init_instance
(mtype
)
757 self.add
("{res} = {res2};")
758 var length
= self.int_instance
(string
.length
)
759 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
760 self.check_init_instance
(res
, mtype
)
761 self.add
("{name} = {res};")
766 # Generate an array value
767 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
769 # Get an instance of a array for a vararg
770 fun vararg_instance
(mpropdef
: MPropDef, recv
: RuntimeVariable, varargs
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
774 # Add a line in the main part of the generated C
775 fun add
(s
: String) do self.writer
.lines
.add
(s
)
778 # (used for local or global declaration)
779 fun add_decl
(s
: String) do self.writer
.decl_lines
.add
(s
)
781 # Return a new local runtime_variable initialized with the C expression `cexpr'.
782 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
784 var res
= new_var
(mtype
)
785 self.add
("{res} = {cexpr};")
789 # Generate generic abort
790 # used by aborts, asserts, casts, etc.
791 fun add_abort
(message
: String)
793 if self.current_node
!= null and self.current_node
.location
.file
!= null then
794 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});")
796 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
801 # Generate a return with the value `s'
802 fun ret
(s
: RuntimeVariable)
804 self.assign
(self.frame
.returnvar
.as(not null), s
)
805 self.add
("goto {self.frame.returnlabel.as(not null)};")
808 # Compile a statement (if any)
809 fun stmt
(nexpr
: nullable AExpr)
811 if nexpr
== null then return
812 var old
= self.current_node
813 self.current_node
= nexpr
815 self.current_node
= old
818 # Compile an expression an return its result
819 # `mtype` is the expected return type, pass null if no specific type is expected.
820 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
822 var old
= self.current_node
823 self.current_node
= nexpr
824 var res
= nexpr
.expr
(self).as(not null)
825 if mtype
!= null then
826 mtype
= self.anchor
(mtype
)
827 res
= self.autobox
(res
, mtype
)
829 res
= autoadapt
(res
, nexpr
.mtype
.as(not null))
830 var implicit_cast_to
= nexpr
.implicit_cast_to
831 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
832 var castres
= self.type_test
(res
, implicit_cast_to
, "auto")
833 self.add
("if (!{castres}) \{")
834 self.add_abort
("Cast failed")
836 res
= autoadapt
(res
, implicit_cast_to
)
838 self.current_node
= old
842 # Alias for `self.expr(nexpr, self.bool_type)'
843 fun expr_bool
(nexpr
: AExpr): RuntimeVariable do return expr
(nexpr
, bool_type
)
845 # Safely show a debug message on the current node and repeat the message in the C code as a comment
846 fun debug
(message
: String)
848 var node
= self.current_node
854 self.add
("/* DEBUG: {message} */")
858 # A C function associated to a Nit method
859 # Because of customization, a given Nit method can be compiler more that once
860 abstract class AbstractRuntimeFunction
862 type COMPILER: AbstractCompiler
863 type VISITOR: AbstractCompilerVisitor
865 # The associated Nit method
866 var mmethoddef
: MMethodDef
868 # The mangled c name of the runtime_function
869 # Subclasses should redefine `build_c_name` instead
872 var res
= self.c_name_cache
873 if res
!= null then return res
874 res
= self.build_c_name
875 self.c_name_cache
= res
879 # Non cached version of `c_name`
880 protected fun build_c_name
: String is abstract
882 protected var c_name_cache
: nullable String writable = null
884 # Implements a call of the runtime_function
885 # May inline the body or generate a C function call
886 fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
888 # Generate the code for the RuntimeFunction
889 # Warning: compile more than once compilation makes CC unhappy
890 fun compile_to_c
(compiler
: COMPILER) is abstract
893 # A runtime variable hold a runtime value in C.
894 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
896 # 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.
897 class RuntimeVariable
898 # The name of the variable in the C code
901 # The static type of the variable (as declard in C)
904 # The current casted type of the variable (as known in Nit)
905 var mcasttype
: MType writable
907 # If the variable exaclty a mcasttype?
908 # false (usual value) means that the variable is a mcasttype or a subtype.
909 var is_exact
: Bool writable = false
911 init(name
: String, mtype
: MType, mcasttype
: MType)
915 self.mcasttype
= mcasttype
916 assert not mtype
.need_anchor
917 assert not mcasttype
.need_anchor
920 redef fun to_s
do return name
925 if self.is_exact
then
931 if self.mtype
== self.mcasttype
then
932 type_str
= "{mtype}{exact_str}"
934 type_str
= "{mtype}({mcasttype}{exact_str})"
936 return "<{name}:{type_str}>"
940 # A frame correspond to a visited property in a GlobalCompilerVisitor
943 type VISITOR: AbstractCompilerVisitor
945 # The associated visitor
948 # The executed property.
949 # A Method in case of a call, an attribute in case of a default initialization.
950 var mpropdef
: MPropDef
952 # The static type of the receiver
953 var receiver
: MClassType
955 # Arguments of the method (the first is the receiver)
956 var arguments
: Array[RuntimeVariable]
958 # The runtime_variable associated to the return (in a function)
959 var returnvar
: nullable RuntimeVariable writable = null
961 # The label at the end of the property
962 var returnlabel
: nullable String writable = null
966 # Mangle a string to be a unique valid C identifier
967 fun to_cmangle
: String
970 var underscore
= false
972 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
978 res
.append
('_'.ascii
.to_s
)
981 if c
>= '0' and c
<= '9' then
984 else if c
== '_' then
989 res
.append
(c
.ascii
.to_s
)
997 # Escape " \ ' and non printable characters for literal C strings or characters
998 fun escape_to_c
: String
1004 else if c
== '\0' then
1006 else if c
== '"' then
1008 else if c == '\'' then
1010 else if c == '\\
' then
1012 else if c.ascii < 32 then
1013 b.append("\\{c.ascii.to_base(8, false)}")
1023 # Return the C type associated to a given Nit static type
1024 fun ctype: String do return "val*"
1026 fun ctypename: String do return "val"
1028 # Return the name of the C structure associated to a Nit live type
1029 fun c_name: String is abstract
1030 protected var c_name_cache: nullable String protected writable
1033 redef class MClassType
1036 var res = self.c_name_cache
1037 if res != null then return res
1038 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
1039 self.c_name_cache = res
1043 redef fun ctype: String
1045 if mclass.name == "Int" then
1047 else if mclass.name == "Bool" then
1049 else if mclass.name == "Char" then
1051 else if mclass.name == "Float" then
1053 else if mclass.name == "NativeString" then
1055 else if mclass.name == "NativeArray" then
1057 else if mclass.kind == extern_kind then
1064 redef fun ctypename: String
1066 if mclass.name == "Int" then
1068 else if mclass.name == "Bool" then
1070 else if mclass.name == "Char" then
1072 else if mclass.name == "Float" then
1074 else if mclass.name == "NativeString" then
1076 else if mclass.name == "NativeArray" then
1077 #return "{self.arguments.first.ctype}*"
1079 else if mclass.kind == extern_kind then
1087 redef class MGenericType
1090 var res = self.c_name_cache
1091 if res != null then return res
1093 for t in self.arguments do
1094 res = res + t.c_name
1096 self.c_name_cache = res
1101 redef class MParameterType
1104 var res = self.c_name_cache
1105 if res != null then return res
1106 res = "{self.mclass.c_name}_FT{self.rank}"
1107 self.c_name_cache = res
1112 redef class MVirtualType
1115 var res = self.c_name_cache
1116 if res != null then return res
1117 res = "{self.mproperty.intro.mclassdef.mclass.c_name}_VT{self.mproperty.name}"
1118 self.c_name_cache = res
1123 redef class MNullableType
1126 var res = self.c_name_cache
1127 if res != null then return res
1128 res = "nullable_{self.mtype.c_name}"
1129 self.c_name_cache = res
1135 # Return the name of the C structure associated to a Nit class
1136 fun c_name: String do
1137 var res = self.c_name_cache
1138 if res != null then return res
1139 res = "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1140 self.c_name_cache = res
1143 private var c_name_cache: nullable String
1146 redef class MProperty
1147 fun c_name: String do
1148 var res = self.c_name_cache
1149 if res != null then return res
1150 res = "{self.intro.c_name}"
1151 self.c_name_cache = res
1154 private var c_name_cache: nullable String
1157 redef class MPropDef
1158 type VISITOR: AbstractCompilerVisitor
1160 private var c_name_cache: nullable String
1162 # The mangled name associated to the property
1165 var res = self.c_name_cache
1166 if res != null then return res
1167 res = "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1168 self.c_name_cache = res
1173 redef class MMethodDef
1174 # Can the body be inlined?
1175 fun can_inline(v: VISITOR): Bool
1177 var modelbuilder = v.compiler.modelbuilder
1178 if modelbuilder.mpropdef2npropdef.has_key(self) then
1179 var npropdef = modelbuilder.mpropdef2npropdef[self]
1180 return npropdef.can_inline
1181 else if self.mproperty.name == "init" then
1182 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1189 # Inline the body in another visitor
1190 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1192 var modelbuilder = v.compiler.modelbuilder
1193 if modelbuilder.mpropdef2npropdef.has_key(self) then
1194 var npropdef = modelbuilder.mpropdef2npropdef[self]
1195 var oldnode = v.current_node
1196 v.current_node = npropdef
1197 self.compile_parameter_check(v, arguments)
1198 npropdef.compile_to_c(v, self, arguments)
1199 v.current_node = oldnode
1200 else if self.mproperty.name == "init" then
1201 var nclassdef = modelbuilder.mclassdef2nclassdef[self.mclassdef]
1202 var oldnode = v.current_node
1203 v.current_node = nclassdef
1204 self.compile_parameter_check(v, arguments)
1205 nclassdef.compile_to_c(v, self, arguments)
1206 v.current_node = oldnode
1213 # Generate type checks in the C code to check covariant parameters
1214 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1216 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1218 for i in [0..msignature.arity[ do
1219 # skip test for vararg since the array is instantiated with the correct polymorphic type
1220 if msignature.vararg_rank == i then continue
1222 # skip if the cast is not required
1223 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1224 if not origmtype.need_anchor then continue
1226 # get the parameter type
1227 var mtype = self.msignature.mparameters[i].mtype
1230 # note that v decides if and how to implements the cast
1231 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1232 var cond = v.type_test(arguments[i+1], mtype, "covariance")
1233 v.add("if (!{cond}) \{")
1234 v.add_abort("Cast failed")
1242 redef class APropdef
1243 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1245 v.add("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1246 debug("Not yet implemented")
1249 fun can_inline: Bool do return true
1252 redef class AConcreteMethPropdef
1253 redef fun compile_to_c(v, mpropdef, arguments)
1255 for i in [0..mpropdef.msignature.arity[ do
1256 var variable = self.n_signature.n_params[i].variable.as(not null)
1257 v.assign(v.variable(variable), arguments[i+1])
1259 # Call the implicit super-init
1260 var auto_super_inits = self.auto_super_inits
1261 if auto_super_inits != null then
1262 var selfarg = [arguments.first]
1263 for auto_super_init in auto_super_inits do
1264 if auto_super_init.intro.msignature.arity == 0 then
1265 v.send(auto_super_init, selfarg)
1267 v.send(auto_super_init, arguments)
1271 v.stmt(self.n_block)
1274 redef fun can_inline
1276 if self.auto_super_inits != null then return false
1277 var nblock = self.n_block
1278 if nblock == null then return true
1279 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1280 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1285 redef class AInternMethPropdef
1286 redef fun compile_to_c(v, mpropdef, arguments)
1288 var pname = mpropdef.mproperty.name
1289 var cname = mpropdef.mclassdef.mclass.name
1290 var ret = mpropdef.msignature.return_mtype
1292 ret = v.resolve_for(ret, arguments.first)
1294 if pname != "==" and pname != "!=" then
1295 v.adapt_signature(mpropdef, arguments)
1297 if cname == "Int" then
1298 if pname == "output" then
1299 v.add("printf(\"%ld\\n\", {arguments.first});")
1301 else if pname == "object_id" then
1302 v.ret(arguments.first)
1304 else if pname == "+" then
1305 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1307 else if pname == "-" then
1308 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1310 else if pname == "unary -" then
1311 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1313 else if pname == "succ" then
1314 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1316 else if pname == "prec" then
1317 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1319 else if pname == "*" then
1320 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1322 else if pname == "/" then
1323 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1325 else if pname == "%" then
1326 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1328 else if pname == "lshift" then
1329 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1331 else if pname == "rshift" then
1332 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1334 else if pname == "==" then
1335 v.ret(v.equal_test(arguments[0], arguments[1]))
1337 else if pname == "!=" then
1338 var res = v.equal_test(arguments[0], arguments[1])
1339 v.ret(v.new_expr("!{res}", ret.as(not null)))
1341 else if pname == "<" then
1342 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1344 else if pname == ">" then
1345 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1347 else if pname == "<=" then
1348 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1350 else if pname == ">=" then
1351 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1353 else if pname == "to_f" then
1354 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
1356 else if pname == "ascii" then
1357 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1360 else if cname == "Char" then
1361 if pname == "output" then
1362 v.add("printf(\"%c\", {arguments.first});")
1364 else if pname == "object_id" then
1365 v.ret(arguments.first)
1367 else if pname == "+" then
1368 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1370 else if pname == "-" then
1371 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1373 else if pname == "==" then
1374 v.ret(v.equal_test(arguments[0], arguments[1]))
1376 else if pname == "!=" then
1377 var res = v.equal_test(arguments[0], arguments[1])
1378 v.ret(v.new_expr("!{res}", ret.as(not null)))
1380 else if pname == "succ" then
1381 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1383 else if pname == "prec" then
1384 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1386 else if pname == "<" then
1387 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1389 else if pname == ">" then
1390 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1392 else if pname == "<=" then
1393 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1395 else if pname == ">=" then
1396 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1398 else if pname == "to_i" then
1399 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
1401 else if pname == "ascii" then
1402 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
1405 else if cname == "Bool" then
1406 if pname == "output" then
1407 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
1409 else if pname == "object_id" then
1410 v.ret(arguments.first)
1412 else if pname == "==" then
1413 v.ret(v.equal_test(arguments[0], arguments[1]))
1415 else if pname == "!=" then
1416 var res = v.equal_test(arguments[0], arguments[1])
1417 v.ret(v.new_expr("!{res}", ret.as(not null)))
1420 else if cname == "Float" then
1421 if pname == "output" then
1422 v.add("printf(\"%f\\n\", {arguments.first});")
1424 else if pname == "object_id" then
1425 v.ret(v.new_expr("(double){arguments.first}", 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 == "-" then
1431 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1433 else if pname == "unary -" then
1434 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1436 else if pname == "succ" then
1437 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1439 else if pname == "prec" then
1440 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1442 else if pname == "*" then
1443 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1445 else if pname == "/" then
1446 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1448 else if pname == "==" then
1449 v.ret(v.equal_test(arguments[0], arguments[1]))
1451 else if pname == "!=" then
1452 var res = v.equal_test(arguments[0], arguments[1])
1453 v.ret(v.new_expr("!{res}", ret.as(not null)))
1455 else if pname == "<" then
1456 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1458 else if pname == ">" then
1459 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1461 else if pname == "<=" then
1462 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1464 else if pname == ">=" then
1465 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1467 else if pname == "to_i" then
1468 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
1471 else if cname == "Char" then
1472 if pname == "output" then
1473 v.add("printf(\"%c\", {arguments.first});")
1475 else if pname == "object_id" then
1476 v.ret(arguments.first)
1478 else if pname == "==" then
1479 v.ret(v.equal_test(arguments[0], arguments[1]))
1481 else if pname == "!=" then
1482 var res = v.equal_test(arguments[0], arguments[1])
1483 v.ret(v.new_expr("!{res}", ret.as(not null)))
1485 else if pname == "ascii" then
1486 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1489 else if cname == "NativeString" then
1490 if pname == "[]" then
1491 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
1493 else if pname == "[]=" then
1494 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1496 else if pname == "copy_to" then
1497 v.add("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1499 else if pname == "atoi" then
1500 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
1503 else if cname == "NativeArray" then
1504 v.native_array_def(pname, ret, arguments)
1507 if pname == "exit" then
1508 v.add("exit({arguments[1]});")
1510 else if pname == "sys" then
1511 v.ret(v.new_expr("glob_sys", ret.as(not null)))
1513 else if pname == "calloc_string" then
1514 v.ret(v.new_expr("(char*)GC_MALLOC_ATOMIC({arguments[1]})", ret.as(not null)))
1516 else if pname == "calloc_array" then
1517 v.calloc_array(ret.as(not null), arguments)
1519 else if pname == "object_id" then
1520 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
1522 else if pname == "is_same_type" then
1523 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
1525 else if pname == "output_class_name" then
1526 var nat = v.class_name_string(arguments.first)
1527 v.add("printf(\"%s\\n\", {nat});")
1529 else if pname == "native_class_name" then
1530 var nat = v.class_name_string(arguments.first)
1531 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
1533 else if pname == "force_garbage_collection" then
1534 v.add("GC_gcollect();")
1537 v.add("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at {location.to_s}\\n\");")
1538 debug("Not implemented {mpropdef}")
1542 redef class AExternMethPropdef
1543 redef fun compile_to_c(v, mpropdef, arguments)
1546 var nextern = self.n_extern
1547 if nextern == null then
1548 v.add("fprintf(stderr, \"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1552 externname = nextern.text.substring(1, nextern.text.length-2)
1553 if location.file != null then
1554 var file = location.file.filename
1555 v.compiler.add_extern(file)
1557 var res: nullable RuntimeVariable = null
1558 var ret = mpropdef.msignature.return_mtype
1560 ret = v.resolve_for(ret, arguments.first)
1561 res = v.new_var(ret)
1563 v.adapt_signature(mpropdef, arguments)
1566 v.add("{externname}({arguments.join(", ")});")
1568 v.add("{res} = {externname}({arguments.join(", ")});")
1574 redef class AExternInitPropdef
1575 redef fun compile_to_c(v, mpropdef, arguments)
1578 var nextern = self.n_extern
1579 if nextern == null then
1580 v.add("printf(\"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1584 externname = nextern.text.substring(1, nextern.text.length-2)
1585 if location.file != null then
1586 var file = location.file.filename
1587 v.compiler.add_extern(file)
1589 v.adapt_signature(mpropdef, arguments)
1590 var ret = arguments.first.mtype
1591 var res = v.new_var(ret)
1595 v.add("{res} = {externname}({arguments.join(", ")});")
1600 redef class AAttrPropdef
1601 redef fun compile_to_c(v, mpropdef, arguments)
1603 if arguments.length == 1 then
1604 var res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
1605 v.assign(v.frame.returnvar.as(not null), res)
1607 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
1611 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1613 var nexpr = self.n_expr
1614 if nexpr != null then
1615 var oldnode = v.current_node
1616 v.current_node = self
1617 var old_frame = v.frame
1618 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1620 var value = v.expr(nexpr, self.mpropdef.static_mtype)
1621 v.write_attribute(self.mpropdef.mproperty, recv, value)
1623 v.current_node = oldnode
1627 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1629 var nexpr = self.n_expr
1630 if nexpr != null then return
1632 var oldnode = v.current_node
1633 v.current_node = self
1634 var old_frame = v.frame
1635 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1637 # Force read to check the initialization
1638 v.read_attribute(self.mpropdef.mproperty, recv)
1640 v.current_node = oldnode
1644 redef class AClassdef
1645 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1647 if mpropdef == self.mfree_init then
1648 var super_inits = self.super_inits
1649 if super_inits != null then
1650 assert arguments.length == 1
1651 for su in super_inits do
1652 v.send(su, arguments)
1656 var recv = arguments.first
1658 # Collect undefined attributes
1659 for npropdef in self.n_propdefs do
1660 if npropdef isa AAttrPropdef and npropdef.n_expr == null then
1661 v.write_attribute(npropdef.mpropdef.mproperty, recv, arguments[i])
1671 redef class ADeferredMethPropdef
1672 redef fun compile_to_c(v, mpropdef, arguments) do v.add_abort("Deferred method called")
1673 redef fun can_inline do return true
1677 # Try to compile self as an expression
1678 # Do not call this method directly, use `v.expr' instead
1679 private fun expr
(v
: AbstractCompilerVisitor): nullable RuntimeVariable
1681 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
1682 var mtype
= self.mtype
1683 if mtype
== null then
1686 var res
= v
.new_var
(mtype
)
1687 v
.add
("/* {res} = NOT YET {class_name} */")
1692 # Try to compile self as a statement
1693 # Do not call this method directly, use `v.stmt' instead
1694 private fun stmt
(v
: AbstractCompilerVisitor)
1697 if res
!= null then v
.add
("{res};")
1701 redef class ABlockExpr
1704 for e
in self.n_expr
do v
.stmt
(e
)
1708 redef class AVardeclExpr
1711 var variable
= self.variable
.as(not null)
1712 var ne
= self.n_expr
1714 var i
= v
.expr
(ne
, variable
.declared_type
)
1715 v
.assign
(v
.variable
(variable
), i
)
1720 redef class AVarExpr
1723 var res
= v
.variable
(self.variable
.as(not null))
1724 var mtype
= self.mtype
.as(not null)
1725 return v
.autoadapt
(res
, mtype
)
1729 redef class AVarAssignExpr
1732 var variable
= self.variable
.as(not null)
1733 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1734 v
.assign
(v
.variable
(variable
), i
)
1738 redef class AVarReassignExpr
1741 var variable
= self.variable
.as(not null)
1742 var vari
= v
.variable
(variable
)
1743 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1744 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [vari
, value
])
1746 v
.assign
(v
.variable
(variable
), res
)
1750 redef class ASelfExpr
1751 redef fun expr
(v
) do return v
.frame
.arguments
.first
1754 redef class AContinueExpr
1755 redef fun stmt
(v
) do v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
1758 redef class ABreakExpr
1759 redef fun stmt
(v
) do v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
1762 redef class AReturnExpr
1765 var nexpr
= self.n_expr
1766 if nexpr
!= null then
1767 var returnvar
= v
.frame
.returnvar
.as(not null)
1768 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
1769 v
.assign
(returnvar
, i
)
1771 v
.add
("goto {v.frame.returnlabel.as(not null)};")
1775 redef class AAbortExpr
1776 redef fun stmt
(v
) do v
.add_abort
("Aborted")
1782 var cond
= v
.expr_bool
(self.n_expr
)
1783 v
.add
("if ({cond})\{")
1791 redef class AIfexprExpr
1794 var res
= v
.new_var
(self.mtype
.as(not null))
1795 var cond
= v
.expr_bool
(self.n_expr
)
1796 v
.add
("if ({cond})\{")
1797 v
.assign
(res
, v
.expr
(self.n_then
, null))
1799 v
.assign
(res
, v
.expr
(self.n_else
, null))
1808 v
.stmt
(self.n_block
)
1809 var escapemark
= self.escapemark
1810 if escapemark
!= null then
1811 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1816 redef class AWhileExpr
1820 var cond
= v
.expr_bool
(self.n_expr
)
1821 v
.add
("if (!{cond}) break;")
1822 v
.stmt
(self.n_block
)
1823 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1825 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1829 redef class ALoopExpr
1833 v
.stmt
(self.n_block
)
1834 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1836 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1840 redef class AForExpr
1843 # Shortcut on explicit range
1844 # Avoid the instantiation of the range and the iterator
1845 var nexpr
= self.n_expr
1846 if self.variables
.length
== 1 and nexpr
isa AOrangeExpr and not v
.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_range
.value
then
1847 var from
= v
.expr
(nexpr
.n_expr
, null)
1848 var to
= v
.expr
(nexpr
.n_expr2
, null)
1849 var variable
= v
.variable
(variables
.first
)
1851 v
.assign
(variable
, from
)
1852 v
.add
("for(;;) \{ /* shortcut range */")
1854 var ok
= v
.send
(v
.get_property
("<", variable
.mtype
), [variable
, to
])
1856 v
.add
("if(!{ok}) break;")
1858 v
.stmt
(self.n_block
)
1860 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1861 var succ
= v
.send
(v
.get_property
("succ", variable
.mtype
), [variable
])
1863 v
.assign
(variable
, succ
)
1865 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1869 var cl
= v
.expr
(self.n_expr
, null)
1870 var it_meth
= self.method_iterator
1871 assert it_meth
!= null
1872 var it
= v
.send
(it_meth
, [cl
])
1875 var isok_meth
= self.method_is_ok
1876 assert isok_meth
!= null
1877 var ok
= v
.send
(isok_meth
, [it
])
1879 v
.add
("if(!{ok}) break;")
1880 if self.variables
.length
== 1 then
1881 var item_meth
= self.method_item
1882 assert item_meth
!= null
1883 var i
= v
.send
(item_meth
, [it
])
1885 v
.assign
(v
.variable
(variables
.first
), i
)
1886 else if self.variables
.length
== 2 then
1887 var key_meth
= self.method_key
1888 assert key_meth
!= null
1889 var i
= v
.send
(key_meth
, [it
])
1891 v
.assign
(v
.variable
(variables
[0]), i
)
1892 var item_meth
= self.method_item
1893 assert item_meth
!= null
1894 i
= v
.send
(item_meth
, [it
])
1896 v
.assign
(v
.variable
(variables
[1]), i
)
1900 v
.stmt
(self.n_block
)
1901 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1902 var next_meth
= self.method_next
1903 assert next_meth
!= null
1904 v
.send
(next_meth
, [it
])
1906 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1910 redef class AAssertExpr
1913 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
1915 var cond
= v
.expr_bool
(self.n_expr
)
1916 v
.add
("if (!{cond}) \{")
1920 v
.add_abort
("Assert '{nid.text}' failed")
1922 v
.add_abort
("Assert failed")
1931 var res
= v
.new_var
(self.mtype
.as(not null))
1932 var i1
= v
.expr_bool
(self.n_expr
)
1933 v
.add
("if ({i1}) \{")
1936 var i2
= v
.expr_bool
(self.n_expr2
)
1937 v
.add
("{res} = {i2};")
1943 redef class AAndExpr
1946 var res
= v
.new_var
(self.mtype
.as(not null))
1947 var i1
= v
.expr_bool
(self.n_expr
)
1948 v
.add
("if (!{i1}) \{")
1951 var i2
= v
.expr_bool
(self.n_expr2
)
1952 v
.add
("{res} = {i2};")
1958 redef class ANotExpr
1961 var cond
= v
.expr_bool
(self.n_expr
)
1962 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
1966 redef class AOrElseExpr
1969 var res
= v
.new_var
(self.mtype
.as(not null))
1970 var i1
= v
.expr
(self.n_expr
, null)
1971 v
.add
("if ({i1}!=NULL) \{")
1974 var i2
= v
.expr
(self.n_expr2
, null)
1984 var value1
= v
.expr
(self.n_expr
, null)
1985 var value2
= v
.expr
(self.n_expr2
, null)
1986 return v
.equal_test
(value1
, value2
)
1990 redef class AIntExpr
1991 redef fun expr
(v
) do return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
1994 redef class AFloatExpr
1995 redef fun expr
(v
) do return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
1998 redef class ACharExpr
1999 redef fun expr
(v
) do return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2002 redef class AArrayExpr
2005 var mtype
= self.mtype
.as(MClassType).arguments
.first
2006 var array
= new Array[RuntimeVariable]
2007 for nexpr
in self.n_exprs
.n_exprs
do
2008 var i
= v
.expr
(nexpr
, mtype
)
2011 return v
.array_instance
(array
, mtype
)
2015 redef class AStringFormExpr
2016 redef fun expr
(v
) do return v
.string_instance
(self.value
.as(not null))
2019 redef class ASuperstringExpr
2022 var array
= new Array[RuntimeVariable]
2023 for ne
in self.n_exprs
do
2024 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2025 var i
= v
.expr
(ne
, null)
2028 var a
= v
.array_instance
(array
, v
.object_type
)
2029 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2034 redef class ACrangeExpr
2037 var i1
= v
.expr
(self.n_expr
, null)
2038 var i2
= v
.expr
(self.n_expr2
, null)
2039 var mtype
= self.mtype
.as(MClassType)
2040 var res
= v
.init_instance
(mtype
)
2041 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2042 v
.check_init_instance
(res
, mtype
)
2047 redef class AOrangeExpr
2050 var i1
= v
.expr
(self.n_expr
, null)
2051 var i2
= v
.expr
(self.n_expr2
, null)
2052 var mtype
= self.mtype
.as(MClassType)
2053 var res
= v
.init_instance
(mtype
)
2054 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2055 v
.check_init_instance
(res
, mtype
)
2060 redef class ATrueExpr
2061 redef fun expr
(v
) do return v
.new_expr
("1", self.mtype
.as(not null))
2064 redef class AFalseExpr
2065 redef fun expr
(v
) do return v
.new_expr
("0", self.mtype
.as(not null))
2068 redef class ANullExpr
2069 redef fun expr
(v
) do return v
.new_expr
("NULL", self.mtype
.as(not null))
2072 redef class AIsaExpr
2075 var i
= v
.expr
(self.n_expr
, null)
2076 return v
.type_test
(i
, self.cast_type
.as(not null), "isa")
2080 redef class AAsCastExpr
2083 var i
= v
.expr
(self.n_expr
, null)
2084 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2086 var cond
= v
.type_test
(i
, self.mtype
.as(not null), "as")
2087 v
.add
("if (!{cond}) \{")
2088 v
.add_abort
("Cast failed")
2094 redef class AAsNotnullExpr
2097 var i
= v
.expr
(self.n_expr
, null)
2098 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2100 v
.add
("if ({i} == NULL) \{")
2101 v
.add_abort
("Cast failed")
2107 redef class AParExpr
2108 redef fun expr
(v
) do return v
.expr
(self.n_expr
, null)
2111 redef class AOnceExpr
2114 var mtype
= self.mtype
.as(not null)
2115 var name
= v
.get_name
("varonce")
2116 var guard
= v
.get_name
(name
+ "_guard")
2117 v
.add_decl
("static {mtype.ctype} {name};")
2118 v
.add_decl
("static int {guard};")
2119 var res
= v
.new_var
(mtype
)
2120 v
.add
("if ({guard}) \{")
2121 v
.add
("{res} = {name};")
2123 var i
= v
.expr
(self.n_expr
, mtype
)
2124 v
.add
("{res} = {i};")
2125 v
.add
("{name} = {res};")
2126 v
.add
("{guard} = 1;")
2132 redef class ASendExpr
2135 var recv
= v
.expr
(self.n_expr
, null)
2137 for a
in self.raw_arguments
.as(not null) do
2138 args
.add
(v
.expr
(a
, null))
2140 return v
.compile_callsite
(self.callsite
.as(not null), args
)
2144 redef class ASendReassignFormExpr
2147 var recv
= v
.expr
(self.n_expr
, null)
2149 for a
in self.raw_arguments
.as(not null) do
2150 args
.add
(v
.expr
(a
, null))
2152 var value
= v
.expr
(self.n_value
, null)
2154 var left
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2157 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [left
, value
])
2161 v
.compile_callsite
(self.write_callsite
.as(not null), args
)
2165 redef class ASuperExpr
2168 var recv
= v
.frame
.arguments
.first
2170 for a
in self.n_args
.n_exprs
do
2171 args
.add
(v
.expr
(a
, null))
2173 if args
.length
== 1 then
2174 args
= v
.frame
.arguments
2177 var mproperty
= self.mproperty
2178 if mproperty
!= null then
2179 if mproperty
.intro
.msignature
.arity
== 0 then
2183 var res
= v
.send
(mproperty
, args
)
2187 # stantard call-next-method
2188 return v
.supercall
(v
.frame
.mpropdef
.as(MMethodDef), recv
.mtype
.as(MClassType), args
)
2192 redef class ANewExpr
2195 var mtype
= self.mtype
.as(MClassType)
2197 var ctype
= mtype
.ctype
2198 if ctype
== "val*" then
2199 recv
= v
.init_instance
(mtype
)
2200 else if ctype
== "void*" then
2201 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2203 debug
("cannot new {mtype}")
2207 for a
in self.n_args
.n_exprs
do
2208 args
.add
(v
.expr
(a
, null))
2210 var res2
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2211 if res2
!= null then
2212 #self.debug("got {res2} from {mproperty}. drop {recv}")
2215 v
.check_init_instance
(recv
, mtype
)
2220 redef class AAttrExpr
2223 var recv
= v
.expr
(self.n_expr
, null)
2224 var mproperty
= self.mproperty
.as(not null)
2225 return v
.read_attribute
(mproperty
, recv
)
2229 redef class AAttrAssignExpr
2232 var recv
= v
.expr
(self.n_expr
, null)
2233 var i
= v
.expr
(self.n_value
, null)
2234 var mproperty
= self.mproperty
.as(not null)
2235 v
.write_attribute
(mproperty
, recv
, i
)
2239 redef class AAttrReassignExpr
2242 var recv
= v
.expr
(self.n_expr
, null)
2243 var value
= v
.expr
(self.n_value
, null)
2244 var mproperty
= self.mproperty
.as(not null)
2245 var attr
= v
.read_attribute
(mproperty
, recv
)
2246 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [attr
, value
])
2248 v
.write_attribute
(mproperty
, recv
, res
)
2252 redef class AIssetAttrExpr
2255 var recv
= v
.expr
(self.n_expr
, null)
2256 var mproperty
= self.mproperty
.as(not null)
2257 return v
.isset_attribute
(mproperty
, recv
)
2261 redef class ADebugTypeExpr
2270 redef class HashSet[E
]
2271 init from
(elements
: Collection[E
]) do
2273 self.add_all
(elements
)
2277 redef class Array[E
]
2278 init from
(elements
: Collection[E
]) do
2280 self.add_all
(elements
)
2283 # Return a new Array with the elements only contened in 'self' and not in 'o'
2284 fun -(o
: Array[E
]): Array[E
] do
2285 var res
= new Array[E
]
2286 for e
in self do if not o
.has
(e
) then res
.add
(e
)
2293 # Return a linearization of a set of mtypes
2294 fun linearize_mtypes
(mtypes
: Set[MType]): Array[MType] do
2295 var lin
= new Array[MType].from
(mtypes
)
2296 var sorter
= new TypeSorter(self)
2301 # Return a reverse linearization of a set of mtypes
2302 fun reverse_linearize_mtypes
(mtypes
: Set[MType]): Array[MType] do
2303 var lin
= new Array[MType].from
(mtypes
)
2304 var sorter
= new ReverseTypeSorter(self)
2309 # Return super types of a `mtype` in `self`
2310 fun super_mtypes
(mtype
: MType, mtypes
: Set[MType]): Set[MType] do
2311 if not self.super_mtypes_cache
.has_key
(mtype
) then
2312 var supers
= new HashSet[MType]
2313 for otype
in mtypes
do
2314 if otype
== mtype
then continue
2315 if mtype
.is_subtype
(self, null, otype
) then
2319 self.super_mtypes_cache
[mtype
] = supers
2321 return self.super_mtypes_cache
[mtype
]
2324 private var super_mtypes_cache
: Map[MType, Set[MType]] = new HashMap[MType, Set[MType]]
2326 # Return all sub mtypes (directs and indirects) of a `mtype` in `self`
2327 fun sub_mtypes
(mtype
: MType, mtypes
: Set[MType]): Set[MType] do
2328 if not self.sub_mtypes_cache
.has_key
(mtype
) then
2329 var subs
= new HashSet[MType]
2330 for otype
in mtypes
do
2331 if otype
== mtype
then continue
2332 if otype
.is_subtype
(self, null, mtype
) then
2336 self.sub_mtypes_cache
[mtype
] = subs
2338 return self.sub_mtypes_cache
[mtype
]
2341 private var sub_mtypes_cache
: Map[MType, Set[MType]] = new HashMap[MType, Set[MType]]
2343 # Return a linearization of a set of mclasses
2344 fun linearize_mclasses_2
(mclasses
: Set[MClass]): Array[MClass] do
2345 var lin
= new Array[MClass].from
(mclasses
)
2346 var sorter
= new ClassSorter(self)
2351 # Return a reverse linearization of a set of mtypes
2352 fun reverse_linearize_mclasses
(mclasses
: Set[MClass]): Array[MClass] do
2353 var lin
= new Array[MClass].from
(mclasses
)
2354 var sorter
= new ReverseClassSorter(self)
2359 # Return all super mclasses (directs and indirects) of a `mclass` in `self`
2360 fun super_mclasses
(mclass
: MClass): Set[MClass] do
2361 if not self.super_mclasses_cache
.has_key
(mclass
) then
2362 var supers
= new HashSet[MClass]
2363 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2364 for sup
in self.flatten_mclass_hierarchy
[mclass
].greaters
do
2365 if sup
== mclass
then continue
2369 self.super_mclasses_cache
[mclass
] = supers
2371 return self.super_mclasses_cache
[mclass
]
2374 private var super_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2376 # Return all parents of a `mclass` in `self`
2377 fun parent_mclasses
(mclass
: MClass): Set[MClass] do
2378 if not self.parent_mclasses_cache
.has_key
(mclass
) then
2379 var parents
= new HashSet[MClass]
2380 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2381 for sup
in self.flatten_mclass_hierarchy
[mclass
].direct_greaters
do
2382 if sup
== mclass
then continue
2386 self.parent_mclasses_cache
[mclass
] = parents
2388 return self.parent_mclasses_cache
[mclass
]
2391 private var parent_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2393 # Return all sub mclasses (directs and indirects) of a `mclass` in `self`
2394 fun sub_mclasses
(mclass
: MClass): Set[MClass] do
2395 if not self.sub_mclasses_cache
.has_key
(mclass
) then
2396 var subs
= new HashSet[MClass]
2397 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2398 for sub
in self.flatten_mclass_hierarchy
[mclass
].smallers
do
2399 if sub
== mclass
then continue
2403 self.sub_mclasses_cache
[mclass
] = subs
2405 return self.sub_mclasses_cache
[mclass
]
2408 private var sub_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2410 # All 'mproperties' associated to all 'mclassdefs' of `mclass`
2411 fun properties
(mclass
: MClass): Set[MProperty] do
2412 if not self.properties_cache
.has_key
(mclass
) then
2413 var properties
= new HashSet[MProperty]
2414 var parents
= self.super_mclasses
(mclass
)
2415 for parent
in parents
do
2416 properties
.add_all
(self.properties
(parent
))
2419 for mclassdef
in mclass
.mclassdefs
do
2420 for mpropdef
in mclassdef
.mpropdefs
do
2421 properties
.add
(mpropdef
.mproperty
)
2424 self.properties_cache
[mclass
] = properties
2426 return properties_cache
[mclass
]
2429 private var properties_cache
: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
2432 # A sorter for linearize list of types
2433 private class TypeSorter
2434 super AbstractSorter[MType]
2436 private var mmodule
: MModule
2438 init(mmodule
: MModule) do self.mmodule
= mmodule
2440 redef fun compare
(a
, b
) do
2443 else if a
.is_subtype
(self.mmodule
, null, b
) then
2450 # A sorter for reverse linearization
2451 private class ReverseTypeSorter
2454 init(mmodule
: MModule) do end
2456 redef fun compare
(a
, b
) do
2459 else if a
.is_subtype
(self.mmodule
, null, b
) then
2466 # A sorter for linearize list of classes
2467 private class ClassSorter
2468 super AbstractSorter[MClass]
2470 var mmodule
: MModule
2472 redef fun compare
(a
, b
) do
2475 else if self.mmodule
.flatten_mclass_hierarchy
.has
(a
) and self.mmodule
.flatten_mclass_hierarchy
[a
].greaters
.has
(b
) then
2482 # A sorter for reverse linearization
2483 private class ReverseClassSorter
2484 super AbstractSorter[MClass]
2486 var mmodule
: MModule
2488 redef fun compare
(a
, b
) do
2491 else if self.mmodule
.flatten_mclass_hierarchy
.has
(a
) and self.mmodule
.flatten_mclass_hierarchy
[a
].greaters
.has
(b
) then