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 var file
: nullable OFStream = null
89 for vis
in compiler
.visitors
do
90 count
+= vis
.lines
.length
91 if file
== null or count
> 10000 or vis
.file_break
then
93 if file
!= null then file
.close
94 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
96 file
= new OFStream.open
(cfilename
)
97 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
98 count
= vis
.lines
.length
100 if vis
!= compiler
.header
then
101 for l
in vis
.decl_lines
do
106 for l
in vis
.lines
do
111 if file
!= null then file
.close
113 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
115 # Generate the Makefile
117 var makename
= ".nit_compile/{mainmodule.name}.mk"
118 var makefile
= new OFStream.open
(makename
)
120 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
121 makefile
.write
("all: {outname}\n\n")
123 var ofiles
= new Array[String]
124 # Compile each generated file
126 var o
= f
.strip_extension
(".c") + ".o"
127 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
130 # Compile each required extern body into a specific .o
131 for f
in compiler
.extern_bodies
do
133 var o
= ".nit_compile/{mainmodule.name}.{i}.o"
134 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
138 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) -o {outname} {ofiles.join(" ")} $(LDLIBS)\n\n")
140 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
142 self.toolcontext
.info
("Generated makefile: {makename}", 2)
145 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
147 # Execute the Makefile
149 if self.toolcontext
.opt_no_cc
.value
then return
152 self.toolcontext
.info
("*** COMPILING C ***", 1)
153 var makeflags
= self.toolcontext
.opt_make_flags
.value
154 if makeflags
== null then makeflags
= ""
155 self.toolcontext
.info
("make -B -f {makename} -j 4 {makeflags}", 2)
158 if self.toolcontext
.verbose_level
>= 3 then
159 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1")
161 res
= sys
.system
("make -B -f {makename} -j 4 {makeflags} 2>&1 >/dev/null")
164 toolcontext
.error
(null, "make failed! Error code: {res}.")
168 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
172 # Singleton that store the knowledge about the compilation process
173 abstract class AbstractCompiler
174 type VISITOR: AbstractCompilerVisitor
176 # The main module of the program
177 var mainmodule
: MModule protected writable
179 # The modeulbuilder used to know the model and the AST
180 var modelbuilder
: ModelBuilder protected writable
182 # Is hardening asked? (see --hardening)
183 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
185 init(mainmodule
: MModule, modelbuilder
: ModelBuilder)
187 self.mainmodule
= mainmodule
188 self.modelbuilder
= modelbuilder
191 # Force the creation of a new file
192 # The point is to avoid contamination between must-be-compiled-separately files
195 var v
= self.new_visitor
199 # The list of all associated visitors
200 # Used to generate .c files
201 # FIXME: should not be vistors but just somewhere to store lines
202 var visitors
: List[VISITOR] = new List[VISITOR]
204 # Initialize a visitor specific for a compiler engine
205 fun new_visitor
: VISITOR is abstract
207 # Where global declaration are stored (the main .h)
209 # FIXME: should not be a visitor but just somewhere to store lines
210 # FIXME: should not have a global .h since it does not help recompilations
211 var header
: VISITOR writable
214 # This method call compile_header_strucs method that has to be refined
215 fun compile_header
do
217 self.header
.add_decl
("#include <stdlib.h>")
218 self.header
.add_decl
("#include <stdio.h>")
219 self.header
.add_decl
("#include <string.h>")
220 self.header
.add_decl
("#ifndef NOBOEHM")
221 self.header
.add_decl
("#include <gc/gc.h>")
222 self.header
.add_decl
("#ifdef NOBOEHM_ATOMIC")
223 self.header
.add_decl
("#undef GC_MALLOC_ATOMIC")
224 self.header
.add_decl
("#define GC_MALLOC_ATOMIC(x) GC_MALLOC(x)")
225 self.header
.add_decl
("#endif /*NOBOEHM_ATOMIC*/")
226 self.header
.add_decl
("#else /*NOBOEHM*/")
227 self.header
.add_decl
("#define GC_MALLOC(x) calloc(1, (x))")
228 self.header
.add_decl
("#define GC_MALLOC_ATOMIC(x) calloc(1, (x))")
229 self.header
.add_decl
("#endif /*NOBOEHM*/")
231 compile_header_structs
233 # Global variable used by the legacy native interface
234 self.header
.add_decl
("extern int glob_argc;")
235 self.header
.add_decl
("extern char **glob_argv;")
236 self.header
.add_decl
("extern val *glob_sys;")
239 # Declaration of structures the live Nit types
240 protected fun compile_header_structs
is abstract
242 # Generate the main C function.
244 # * allocate the Sys object if it exists
245 # * call init if is exists
246 # * call main if it exists
247 fun compile_main_function
249 var v
= self.new_visitor
250 v
.add_decl
("int glob_argc;")
251 v
.add_decl
("char **glob_argv;")
252 v
.add_decl
("val *glob_sys;")
254 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
255 for tag
in count_type_test_tags
do
256 v
.add_decl
("long count_type_test_resolved_{tag};")
257 v
.add_decl
("long count_type_test_unresolved_{tag};")
258 v
.add_decl
("long count_type_test_skipped_{tag};")
259 v
.compiler
.header
.add_decl
("extern long count_type_test_resolved_{tag};")
260 v
.compiler
.header
.add_decl
("extern long count_type_test_unresolved_{tag};")
261 v
.compiler
.header
.add_decl
("extern long count_type_test_skipped_{tag};")
264 v
.add_decl
("int main(int argc, char** argv) \{")
265 v
.add
("glob_argc = argc; glob_argv = argv;")
266 var main_type
= mainmodule
.sys_type
267 if main_type
!= null then
268 var mainmodule
= v
.compiler
.mainmodule
269 var glob_sys
= v
.init_instance
(main_type
)
270 v
.add
("glob_sys = {glob_sys};")
271 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
272 if main_init
!= null then
273 v
.send
(main_init
, [glob_sys
])
275 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
276 if main_method
!= null then
277 v
.send
(main_method
, [glob_sys
])
281 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
282 v
.add_decl
("long count_type_test_resolved_total = 0;")
283 v
.add_decl
("long count_type_test_unresolved_total = 0;")
284 v
.add_decl
("long count_type_test_skipped_total = 0;")
285 v
.add_decl
("long count_type_test_total_total = 0;")
286 for tag
in count_type_test_tags
do
287 v
.add_decl
("long count_type_test_total_{tag};")
288 v
.add
("count_type_test_total_{tag} = count_type_test_resolved_{tag} + count_type_test_unresolved_{tag} + count_type_test_skipped_{tag};")
289 v
.add
("count_type_test_resolved_total += count_type_test_resolved_{tag};")
290 v
.add
("count_type_test_unresolved_total += count_type_test_unresolved_{tag};")
291 v
.add
("count_type_test_skipped_total += count_type_test_skipped_{tag};")
292 v
.add
("count_type_test_total_total += count_type_test_total_{tag};")
294 v
.add
("printf(\"# dynamic count_type_test: total %l\\n\");")
295 v
.add
("printf(\"\\tresolved\\tunresolved\\tskipped\\ttotal\\n\
");")
296 var tags
= count_type_test_tags
.to_a
299 v
.add
("printf(\"{tag}\
");")
300 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_resolved_{tag}, 100.0*count_type_test_resolved_{tag}/count_type_test_total_total);")
301 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_unresolved_{tag}, 100.0*count_type_test_unresolved_{tag}/count_type_test_total_total);")
302 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\
", count_type_test_skipped_{tag}, 100.0*count_type_test_skipped_{tag}/count_type_test_total_total);")
303 v
.add
("printf(\"\\t
%ld
(%.2f
%%)\\n\
", count_type_test_total_{tag}, 100.0*count_type_test_total_{tag}/count_type_test_total_total);")
310 # look for a needed .h and .c file for a given .nit source-file
311 # FIXME: bad API, parameter should be a MModule, not its source-file
312 fun add_extern
(file
: String)
314 file
= file
.strip_extension
(".nit")
315 var tryfile
= file
+ ".nit.h"
316 if tryfile
.file_exists
then
317 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
319 tryfile
= file
+ "_nit.h"
320 if tryfile
.file_exists
then
321 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
323 tryfile
= file
+ ".nit.c"
324 if tryfile
.file_exists
then
325 self.extern_bodies
.add
(tryfile
)
327 tryfile
= file
+ "_nit.c"
328 if tryfile
.file_exists
then
329 self.extern_bodies
.add
(tryfile
)
333 # List of additional .c files required to compile (native interface)
334 var extern_bodies
= new ArraySet[String]
336 # Generate code that check if an instance is correctly initialized
337 fun generate_check_init_instance
(mtype
: MClassType) is abstract
339 # Generate code that initialize the attributes on a new instance
340 fun generate_init_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
342 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
343 self.mainmodule
.linearize_mclassdefs
(cds
)
345 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
346 for npropdef
in n
.n_propdefs
do
347 if npropdef
isa AAttrPropdef then
348 npropdef
.init_expr
(v
, recv
)
354 # Generate code that check if an attribute is correctly initialized
355 fun generate_check_attr
(v
: VISITOR, recv
: RuntimeVariable, mtype
: MClassType)
357 var cds
= mtype
.collect_mclassdefs
(self.mainmodule
).to_a
358 self.mainmodule
.linearize_mclassdefs
(cds
)
360 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
361 for npropdef
in n
.n_propdefs
do
362 if npropdef
isa AAttrPropdef then
363 npropdef
.check_expr
(v
, recv
)
371 var count_type_test_tags
: Array[String] = ["isa", "as", "auto", "covariance", "erasure"]
372 var count_type_test_resolved
: HashMap[String, Int] = init_count_type_test_tags
373 var count_type_test_unresolved
: HashMap[String, Int] = init_count_type_test_tags
374 var count_type_test_skipped
: HashMap[String, Int] = init_count_type_test_tags
376 protected fun init_count_type_test_tags
: HashMap[String, Int]
378 var res
= new HashMap[String, Int]
379 for tag
in count_type_test_tags
do
385 # Display stats about compilation process
387 # * type tests against resolved types (x isa Collection[Animal])
388 # * type tests against unresolved types (x isa Collection[E])
389 # * type tests skipped
394 if self.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
395 print
"# static count_type_test"
396 print
"\tresolved:\tunresolved\tskipped\ttotal"
397 var count_type_test_total
= init_count_type_test_tags
398 count_type_test_resolved
["total"] = 0
399 count_type_test_unresolved
["total"] = 0
400 count_type_test_skipped
["total"] = 0
401 count_type_test_total
["total"] = 0
402 for tag
in count_type_test_tags
do
403 count_type_test_total
[tag
] = count_type_test_resolved
[tag
] + count_type_test_unresolved
[tag
] + count_type_test_skipped
[tag
]
404 count_type_test_resolved
["total"] += count_type_test_resolved
[tag
]
405 count_type_test_unresolved
["total"] += count_type_test_unresolved
[tag
]
406 count_type_test_skipped
["total"] += count_type_test_skipped
[tag
]
407 count_type_test_total
["total"] += count_type_test_total
[tag
]
409 var count_type_test
= count_type_test_total
["total"]
410 var tags
= count_type_test_tags
.to_a
414 printn
"\t{count_type_test_resolved[tag]} ({div(count_type_test_resolved[tag],count_type_test)}%)"
415 printn
"\t{count_type_test_unresolved[tag]} ({div(count_type_test_unresolved[tag],count_type_test)}%)"
416 printn
"\t{count_type_test_skipped[tag]} ({div(count_type_test_skipped[tag],count_type_test)}%)"
417 printn
"\t{count_type_test_total[tag]} ({div(count_type_test_total[tag],count_type_test)}%)"
424 # Avoid division by zero by returning the string "n/a"
425 fun div
(a
,b
:Int):String
427 if b
== 0 then return "n/a"
428 return ((a
*10000/b
).to_f
/ 100.0).to_precision
(2)
432 # A visitor on the AST of property definition that generate the C code.
433 abstract class AbstractCompilerVisitor
435 type COMPILER: AbstractCompiler
437 # The associated compiler
438 var compiler
: COMPILER
440 # The current visited AST node
441 var current_node
: nullable ANode writable = null
444 var frame
: nullable Frame writable
446 # Alias for self.compiler.mainmodule.object_type
447 fun object_type
: MClassType do return self.compiler
.mainmodule
.object_type
449 # Alias for self.compiler.mainmodule.bool_type
450 fun bool_type
: MClassType do return self.compiler
.mainmodule
.bool_type
452 var file_break
: Bool = false
454 init(compiler
: COMPILER)
456 self.compiler
= compiler
457 compiler
.visitors
.add
(self)
460 # Force to get the primitive class named `name' or abort
461 fun get_class
(name
: String): MClass do return self.compiler
.mainmodule
.get_primitive_class
(name
)
463 # Force to get the primitive property named `name' in the instance `recv' or abort
464 fun get_property
(name
: String, recv
: MType): MMethod
466 return self.compiler
.modelbuilder
.force_get_primitive_method
(self.current_node
.as(not null), name
, recv
, self.compiler
.mainmodule
)
469 fun compile_callsite
(callsite
: CallSite, args
: Array[RuntimeVariable]): nullable RuntimeVariable
471 return self.send
(callsite
.mproperty
, args
)
474 fun calloc_array
(ret_type
: MType, arguments
: Array[RuntimeVariable]) is abstract
476 fun native_array_def
(pname
: String, ret_type
: nullable MType, arguments
: Array[RuntimeVariable]) is abstract
478 # Transform varargs, in raw arguments, into a single argument of type Array
479 # Note: this method modify the given `args`
480 # If there is no vararg, then `args` is not modified.
481 fun varargize
(mpropdef
: MPropDef, msignature
: MSignature, args
: Array[RuntimeVariable])
483 var recv
= args
.first
484 var vararg_rank
= msignature
.vararg_rank
485 if vararg_rank
>= 0 then
486 assert args
.length
>= msignature
.arity
+ 1 # because of self
488 args
= new Array[RuntimeVariable]
490 args
.add
(rawargs
.first
) # recv
492 for i
in [0..vararg_rank
[ do
493 args
.add
(rawargs
[i
+1])
496 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-msignature
.arity
497 var vararg
= new Array[RuntimeVariable]
498 for i
in [vararg_rank
..vararg_lastrank
] do
499 vararg
.add
(rawargs
[i
+1])
502 var elttype
= msignature
.mparameters
[vararg_rank
].mtype
503 args
.add
(self.vararg_instance
(mpropdef
, recv
, vararg
, elttype
))
505 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
506 args
.add
(rawargs
[i
+1])
509 rawargs
.add_all
(args
)
515 # Anchor a type to the main module and the current receiver
516 fun anchor
(mtype
: MType): MType
518 if not mtype
.need_anchor
then return mtype
519 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
522 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
524 if not mtype
.need_anchor
then return mtype
525 return mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
528 # Unsafely cast a value to a new type
529 # ie the result share the same C variable but my have a different mcasttype
530 # NOTE: if the adaptation is useless then `value' is returned as it.
531 # ENSURE: return.name == value.name
532 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
534 mtype
= self.anchor
(mtype
)
535 var valmtype
= value
.mcasttype
536 if valmtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
540 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
541 var res
= new RuntimeVariable(value
.name
, valmtype
, valmtype
.mtype
)
544 var res
= new RuntimeVariable(value
.name
, valmtype
, mtype
)
549 # Generate a super call from a method definition
550 fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
552 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable]) is abstract
554 # Box or unbox a value to another type iff a C type conversion is needed
555 # ENSURE: result.mtype.ctype == mtype.ctype
556 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable is abstract
558 # Generate a polymorphic subtype test
559 fun type_test
(value
: RuntimeVariable, mtype
: MType, tag
: String): RuntimeVariable is abstract
561 # Generate the code required to dynamically check if 2 objects share the same runtime type
562 fun is_same_type_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
564 # Generate a Nit "is" for two runtime_variables
565 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable is abstract
569 # Generate a static call on a method definition
570 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
572 # Generate a polymorphic send for the method `m' and the arguments `args'
573 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
575 # Generate a monomorphic send for the method `m', the type `t' and the arguments `args'
576 fun monomorphic_send
(m
: MMethod, t
: MType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
578 assert t
isa MClassType
579 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
580 return self.call
(propdef
, t
, args
)
583 # Attributes handling
585 # Generate a polymorphic attribute is_set test
586 fun isset_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
588 # Generate a polymorphic attribute read
589 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable is abstract
591 # Generate a polymorphic attribute write
592 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable) is abstract
596 # Add a check and an abort for a null reciever if needed
597 fun check_recv_notnull
(recv
: RuntimeVariable)
599 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then return
601 var maybenull
= recv
.mcasttype
isa MNullableType or recv
.mcasttype
isa MNullType
603 self.add
("if ({recv} == NULL) \{")
604 self.add_abort
("Reciever is null")
609 # Generate a check-init-instance
610 fun check_init_instance
(recv
: RuntimeVariable, mtype
: MClassType) is abstract
614 private var names
: HashSet[String] = new HashSet[String]
615 private var last
: Int = 0
617 # Return a new name based on `s' and unique in the visitor
618 fun get_name
(s
: String): String
620 if not self.names
.has
(s
) then
624 var i
= self.last
+ 1
627 if not self.names
.has
(s2
) then
636 # Return an unique and stable identifier associated with an escapemark
637 fun escapemark_name
(e
: nullable EscapeMark): String
640 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
642 if name
== null then name
= "label"
643 name
= get_name
(name
)
644 escapemark_names
[e
] = name
648 private var escapemark_names
= new HashMap[EscapeMark, String]
650 # Return a "const char*" variable associated to the classname of the dynamic type of an object
651 # NOTE: we do not return a RuntimeVariable "NativeString" as the class may not exist in the module/program
652 fun class_name_string
(value
: RuntimeVariable): String is abstract
656 protected var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
658 # Return the local runtime_variable associated to a Nit local variable
659 fun variable
(variable
: Variable): RuntimeVariable
661 if self.variables
.has_key
(variable
) then
662 return self.variables
[variable
]
664 var name
= self.get_name
("var_{variable.name}")
665 var mtype
= variable
.declared_type
.as(not null)
666 mtype
= self.anchor
(mtype
)
667 var res
= new RuntimeVariable(name
, mtype
, mtype
)
668 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
669 self.variables
[variable
] = res
674 # Return a new uninitialized local runtime_variable
675 fun new_var
(mtype
: MType): RuntimeVariable
677 mtype
= self.anchor
(mtype
)
678 var name
= self.get_name
("var")
679 var res
= new RuntimeVariable(name
, mtype
, mtype
)
680 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
684 # Return a new uninitialized named runtime_variable
685 fun new_named_var
(mtype
: MType, name
: String): RuntimeVariable
687 mtype
= self.anchor
(mtype
)
688 var res
= new RuntimeVariable(name
, mtype
, mtype
)
689 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
693 # Correctly assign a left and a right value
694 # Boxing and unboxing is performed if required
695 fun assign
(left
, right
: RuntimeVariable)
697 right
= self.autobox
(right
, left
.mtype
)
698 self.add
("{left} = {right};")
703 # Generate a alloc-instance + init-attributes
704 fun init_instance
(mtype
: MClassType): RuntimeVariable is abstract
706 # Generate an integer value
707 fun int_instance
(value
: Int): RuntimeVariable
709 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
710 self.add
("{res} = {value};")
714 # Generate a string value
715 fun string_instance
(string
: String): RuntimeVariable
717 var mtype
= self.get_class
("String").mclass_type
718 var name
= self.get_name
("varonce")
719 self.add_decl
("static {mtype.ctype} {name};")
720 var res
= self.new_var
(mtype
)
721 self.add
("if ({name}) \{")
722 self.add
("{res} = {name};")
723 self.add
("\} else \{")
724 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
725 self.add
("{nat} = \"{string.escape_to_c}\
";")
726 var res2
= self.init_instance
(mtype
)
727 self.add
("{res} = {res2};")
728 var length
= self.int_instance
(string
.length
)
729 self.send
(self.get_property
("with_native", mtype
), [res
, nat
, length
])
730 self.check_init_instance
(res
, mtype
)
731 self.add
("{name} = {res};")
736 # Generate an array value
737 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
739 # Get an instance of a array for a vararg
740 fun vararg_instance
(mpropdef
: MPropDef, recv
: RuntimeVariable, varargs
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable is abstract
744 private var lines
: List[String] = new List[String]
745 private var decl_lines
: List[String] = new List[String]
747 # Add a line in the main part of the generated C
748 fun add
(s
: String) do self.lines
.add
(s
)
751 # (used for local or global declaration)
752 fun add_decl
(s
: String) do self.decl_lines
.add
(s
)
754 # Return a new local runtime_variable initialized with the C expression `cexpr'.
755 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
757 var res
= new_var
(mtype
)
758 self.add
("{res} = {cexpr};")
762 # Generate generic abort
763 # used by aborts, asserts, casts, etc.
764 fun add_abort
(message
: String)
766 if self.current_node
!= null and self.current_node
.location
.file
!= null then
767 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});")
769 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
774 # Generate a return with the value `s'
775 fun ret
(s
: RuntimeVariable)
777 self.assign
(self.frame
.returnvar
.as(not null), s
)
778 self.add
("goto {self.frame.returnlabel.as(not null)};")
781 # Compile a statement (if any)
782 fun stmt
(nexpr
: nullable AExpr)
784 if nexpr
== null then return
785 var old
= self.current_node
786 self.current_node
= nexpr
788 self.current_node
= old
791 # Compile an expression an return its result
792 # `mtype` is the expected return type, pass null if no specific type is expected.
793 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
795 var old
= self.current_node
796 self.current_node
= nexpr
797 var res
= nexpr
.expr
(self).as(not null)
798 if mtype
!= null then
799 mtype
= self.anchor
(mtype
)
800 res
= self.autobox
(res
, mtype
)
802 res
= autoadapt
(res
, nexpr
.mtype
.as(not null))
803 var implicit_cast_to
= nexpr
.implicit_cast_to
804 if implicit_cast_to
!= null and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_autocast
.value
then
805 var castres
= self.type_test
(res
, implicit_cast_to
, "auto")
806 self.add
("if (!{castres}) \{")
807 self.add_abort
("Cast failed")
809 res
= autoadapt
(res
, implicit_cast_to
)
811 self.current_node
= old
815 # Alias for `self.expr(nexpr, self.bool_type)'
816 fun expr_bool
(nexpr
: AExpr): RuntimeVariable do return expr
(nexpr
, bool_type
)
818 # Safely show a debug message on the current node and repeat the message in the C code as a comment
819 fun debug
(message
: String)
821 var node
= self.current_node
827 self.add
("/* DEBUG: {message} */")
831 # A C function associated to a Nit method
832 # Because of customization, a given Nit method can be compiler more that once
833 abstract class AbstractRuntimeFunction
835 type COMPILER: AbstractCompiler
836 type VISITOR: AbstractCompilerVisitor
838 # The associated Nit method
839 var mmethoddef
: MMethodDef
841 # The mangled c name of the runtime_function
842 # Subclasses should redefine `build_c_name` instead
845 var res
= self.c_name_cache
846 if res
!= null then return res
847 res
= self.build_c_name
848 self.c_name_cache
= res
852 # Non cached version of `c_name`
853 protected fun build_c_name
: String is abstract
855 protected var c_name_cache
: nullable String writable = null
857 # Implements a call of the runtime_function
858 # May inline the body or generate a C function call
859 fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
861 # Generate the code for the RuntimeFunction
862 # Warning: compile more than once compilation makes CC unhappy
863 fun compile_to_c
(compiler
: COMPILER) is abstract
866 # A runtime variable hold a runtime value in C.
867 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
869 # 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.
870 class RuntimeVariable
871 # The name of the variable in the C code
874 # The static type of the variable (as declard in C)
877 # The current casted type of the variable (as known in Nit)
878 var mcasttype
: MType writable
880 # If the variable exaclty a mcasttype?
881 # false (usual value) means that the variable is a mcasttype or a subtype.
882 var is_exact
: Bool writable = false
884 init(name
: String, mtype
: MType, mcasttype
: MType)
888 self.mcasttype
= mcasttype
889 assert not mtype
.need_anchor
890 assert not mcasttype
.need_anchor
893 redef fun to_s
do return name
898 if self.is_exact
then
904 if self.mtype
== self.mcasttype
then
905 type_str
= "{mtype}{exact_str}"
907 type_str
= "{mtype}({mcasttype}{exact_str})"
909 return "<{name}:{type_str}>"
913 # A frame correspond to a visited property in a GlobalCompilerVisitor
916 type VISITOR: AbstractCompilerVisitor
918 # The associated visitor
921 # The executed property.
922 # A Method in case of a call, an attribute in case of a default initialization.
923 var mpropdef
: MPropDef
925 # The static type of the receiver
926 var receiver
: MClassType
928 # Arguments of the method (the first is the receiver)
929 var arguments
: Array[RuntimeVariable]
931 # The runtime_variable associated to the return (in a function)
932 var returnvar
: nullable RuntimeVariable writable = null
934 # The label at the end of the property
935 var returnlabel
: nullable String writable = null
939 # Mangle a string to be a unique valid C identifier
940 fun to_cmangle
: String
943 var underscore
= false
945 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
951 res
.append
('_'.ascii
.to_s
)
954 if c
>= '0' and c
<= '9' then
957 else if c
== '_' then
962 res
.append
(c
.ascii
.to_s
)
970 # Escape " \ ' and non printable characters for literal C strings or characters
971 fun escape_to_c
: String
977 else if c
== '\0' then
979 else if c
== '"' then
981 else if c == '\'' then
983 else if c == '\\
' then
985 else if c.ascii < 32 then
986 b.append("\\{c.ascii.to_base(8, false)}")
996 # Return the C type associated to a given Nit static type
997 fun ctype: String do return "val*"
999 fun ctypename: String do return "val"
1001 # Return the name of the C structure associated to a Nit live type
1002 fun c_name: String is abstract
1003 protected var c_name_cache: nullable String protected writable
1006 redef class MClassType
1009 var res = self.c_name_cache
1010 if res != null then return res
1011 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
1012 self.c_name_cache = res
1016 redef fun ctype: String
1018 if mclass.name == "Int" then
1020 else if mclass.name == "Bool" then
1022 else if mclass.name == "Char" then
1024 else if mclass.name == "Float" then
1026 else if mclass.name == "NativeString" then
1028 else if mclass.name == "NativeArray" then
1030 else if mclass.kind == extern_kind then
1037 redef fun ctypename: String
1039 if mclass.name == "Int" then
1041 else if mclass.name == "Bool" then
1043 else if mclass.name == "Char" then
1045 else if mclass.name == "Float" then
1047 else if mclass.name == "NativeString" then
1049 else if mclass.name == "NativeArray" then
1050 #return "{self.arguments.first.ctype}*"
1052 else if mclass.kind == extern_kind then
1060 redef class MGenericType
1063 var res = self.c_name_cache
1064 if res != null then return res
1066 for t in self.arguments do
1067 res = res + t.c_name
1069 self.c_name_cache = res
1074 redef class MParameterType
1077 var res = self.c_name_cache
1078 if res != null then return res
1079 res = "{self.mclass.c_name}_FT{self.rank}"
1080 self.c_name_cache = res
1085 redef class MVirtualType
1088 var res = self.c_name_cache
1089 if res != null then return res
1090 res = "{self.mproperty.intro.mclassdef.mclass.c_name}_VT{self.mproperty.name}"
1091 self.c_name_cache = res
1096 redef class MNullableType
1099 var res = self.c_name_cache
1100 if res != null then return res
1101 res = "nullable_{self.mtype.c_name}"
1102 self.c_name_cache = res
1108 # Return the name of the C structure associated to a Nit class
1109 fun c_name: String do
1110 var res = self.c_name_cache
1111 if res != null then return res
1112 res = "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1113 self.c_name_cache = res
1116 private var c_name_cache: nullable String
1119 redef class MProperty
1120 fun c_name: String do
1121 var res = self.c_name_cache
1122 if res != null then return res
1123 res = "{self.intro.c_name}"
1124 self.c_name_cache = res
1127 private var c_name_cache: nullable String
1130 redef class MPropDef
1131 type VISITOR: AbstractCompilerVisitor
1133 private var c_name_cache: nullable String
1135 # The mangled name associated to the property
1138 var res = self.c_name_cache
1139 if res != null then return res
1140 res = "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1141 self.c_name_cache = res
1146 redef class MMethodDef
1147 # Can the body be inlined?
1148 fun can_inline(v: VISITOR): Bool
1150 var modelbuilder = v.compiler.modelbuilder
1151 if modelbuilder.mpropdef2npropdef.has_key(self) then
1152 var npropdef = modelbuilder.mpropdef2npropdef[self]
1153 return npropdef.can_inline
1154 else if self.mproperty.name == "init" then
1155 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1162 # Inline the body in another visitor
1163 fun compile_inside_to_c(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1165 var modelbuilder = v.compiler.modelbuilder
1166 if modelbuilder.mpropdef2npropdef.has_key(self) then
1167 var npropdef = modelbuilder.mpropdef2npropdef[self]
1168 var oldnode = v.current_node
1169 v.current_node = npropdef
1170 self.compile_parameter_check(v, arguments)
1171 npropdef.compile_to_c(v, self, arguments)
1172 v.current_node = oldnode
1173 else if self.mproperty.name == "init" then
1174 var nclassdef = modelbuilder.mclassdef2nclassdef[self.mclassdef]
1175 var oldnode = v.current_node
1176 v.current_node = nclassdef
1177 self.compile_parameter_check(v, arguments)
1178 nclassdef.compile_to_c(v, self, arguments)
1179 v.current_node = oldnode
1186 # Generate type checks in the C code to check covariant parameters
1187 fun compile_parameter_check(v: VISITOR, arguments: Array[RuntimeVariable])
1189 if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
1191 for i in [0..msignature.arity[ do
1192 # skip test for vararg since the array is instantiated with the correct polymorphic type
1193 if msignature.vararg_rank == i then continue
1195 # skip if the cast is not required
1196 var origmtype = self.mproperty.intro.msignature.mparameters[i].mtype
1197 if not origmtype.need_anchor then continue
1199 # get the parameter type
1200 var mtype = self.msignature.mparameters[i].mtype
1203 # note that v decides if and how to implements the cast
1204 v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
1205 var cond = v.type_test(arguments[i+1], mtype, "covariance")
1206 v.add("if (!{cond}) \{")
1207 v.add_abort("Cast failed")
1215 redef class APropdef
1216 fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1218 v.add("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at {location.to_s}\\n\");")
1219 debug("Not yet implemented")
1222 fun can_inline: Bool do return true
1225 redef class AConcreteMethPropdef
1226 redef fun compile_to_c(v, mpropdef, arguments)
1228 for i in [0..mpropdef.msignature.arity[ do
1229 var variable = self.n_signature.n_params[i].variable.as(not null)
1230 v.assign(v.variable(variable), arguments[i+1])
1232 # Call the implicit super-init
1233 var auto_super_inits = self.auto_super_inits
1234 if auto_super_inits != null then
1235 var selfarg = [arguments.first]
1236 for auto_super_init in auto_super_inits do
1237 if auto_super_init.intro.msignature.arity == 0 then
1238 v.send(auto_super_init, selfarg)
1240 v.send(auto_super_init, arguments)
1244 v.stmt(self.n_block)
1247 redef fun can_inline
1249 if self.auto_super_inits != null then return false
1250 var nblock = self.n_block
1251 if nblock == null then return true
1252 if (mpropdef.mproperty.name == "==" or mpropdef.mproperty.name == "!=") and mpropdef.mclassdef.mclass.name == "Object" then return true
1253 if nblock isa ABlockExpr and nblock.n_expr.length == 0 then return true
1258 redef class AInternMethPropdef
1259 redef fun compile_to_c(v, mpropdef, arguments)
1261 var pname = mpropdef.mproperty.name
1262 var cname = mpropdef.mclassdef.mclass.name
1263 var ret = mpropdef.msignature.return_mtype
1265 ret = v.resolve_for(ret, arguments.first)
1267 if pname != "==" and pname != "!=" then
1268 v.adapt_signature(mpropdef, arguments)
1270 if cname == "Int" then
1271 if pname == "output" then
1272 v.add("printf(\"%ld\\n\", {arguments.first});")
1274 else if pname == "object_id" then
1275 v.ret(arguments.first)
1277 else if pname == "+" then
1278 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1280 else if pname == "-" then
1281 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1283 else if pname == "unary -" then
1284 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1286 else if pname == "succ" then
1287 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1289 else if pname == "prec" then
1290 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1292 else if pname == "*" then
1293 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1295 else if pname == "/" then
1296 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1298 else if pname == "%" then
1299 v.ret(v.new_expr("{arguments[0]} % {arguments[1]}", ret.as(not null)))
1301 else if pname == "lshift" then
1302 v.ret(v.new_expr("{arguments[0]} << {arguments[1]}", ret.as(not null)))
1304 else if pname == "rshift" then
1305 v.ret(v.new_expr("{arguments[0]} >> {arguments[1]}", ret.as(not null)))
1307 else if pname == "==" then
1308 v.ret(v.equal_test(arguments[0], arguments[1]))
1310 else if pname == "!=" then
1311 var res = v.equal_test(arguments[0], arguments[1])
1312 v.ret(v.new_expr("!{res}", ret.as(not null)))
1314 else if pname == "<" then
1315 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1317 else if pname == ">" then
1318 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1320 else if pname == "<=" then
1321 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1323 else if pname == ">=" then
1324 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1326 else if pname == "to_f" then
1327 v.ret(v.new_expr("(double){arguments[0]}", ret.as(not null)))
1329 else if pname == "ascii" then
1330 v.ret(v.new_expr("{arguments[0]}", ret.as(not null)))
1333 else if cname == "Char" then
1334 if pname == "output" then
1335 v.add("printf(\"%c\", {arguments.first});")
1337 else if pname == "object_id" then
1338 v.ret(arguments.first)
1340 else if pname == "+" then
1341 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1343 else if pname == "-" then
1344 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1346 else if pname == "==" then
1347 v.ret(v.equal_test(arguments[0], arguments[1]))
1349 else if pname == "!=" then
1350 var res = v.equal_test(arguments[0], arguments[1])
1351 v.ret(v.new_expr("!{res}", ret.as(not null)))
1353 else if pname == "succ" then
1354 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1356 else if pname == "prec" then
1357 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1359 else if pname == "<" then
1360 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1362 else if pname == ">" then
1363 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1365 else if pname == "<=" then
1366 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1368 else if pname == ">=" then
1369 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1371 else if pname == "to_i" then
1372 v.ret(v.new_expr("{arguments[0]}-'0'", ret.as(not null)))
1374 else if pname == "ascii" then
1375 v.ret(v.new_expr("(unsigned char){arguments[0]}", ret.as(not null)))
1378 else if cname == "Bool" then
1379 if pname == "output" then
1380 v.add("printf({arguments.first}?\"true\\n\":\"false\\n\");")
1382 else if pname == "object_id" then
1383 v.ret(arguments.first)
1385 else if pname == "==" then
1386 v.ret(v.equal_test(arguments[0], arguments[1]))
1388 else if pname == "!=" then
1389 var res = v.equal_test(arguments[0], arguments[1])
1390 v.ret(v.new_expr("!{res}", ret.as(not null)))
1393 else if cname == "Float" then
1394 if pname == "output" then
1395 v.add("printf(\"%f\\n\", {arguments.first});")
1397 else if pname == "object_id" then
1398 v.ret(v.new_expr("(double){arguments.first}", ret.as(not null)))
1400 else if pname == "+" then
1401 v.ret(v.new_expr("{arguments[0]} + {arguments[1]}", ret.as(not null)))
1403 else if pname == "-" then
1404 v.ret(v.new_expr("{arguments[0]} - {arguments[1]}", ret.as(not null)))
1406 else if pname == "unary -" then
1407 v.ret(v.new_expr("-{arguments[0]}", ret.as(not null)))
1409 else if pname == "succ" then
1410 v.ret(v.new_expr("{arguments[0]}+1", ret.as(not null)))
1412 else if pname == "prec" then
1413 v.ret(v.new_expr("{arguments[0]}-1", ret.as(not null)))
1415 else if pname == "*" then
1416 v.ret(v.new_expr("{arguments[0]} * {arguments[1]}", ret.as(not null)))
1418 else if pname == "/" then
1419 v.ret(v.new_expr("{arguments[0]} / {arguments[1]}", ret.as(not null)))
1421 else if pname == "==" then
1422 v.ret(v.equal_test(arguments[0], arguments[1]))
1424 else if pname == "!=" then
1425 var res = v.equal_test(arguments[0], arguments[1])
1426 v.ret(v.new_expr("!{res}", ret.as(not null)))
1428 else if pname == "<" then
1429 v.ret(v.new_expr("{arguments[0]} < {arguments[1]}", ret.as(not null)))
1431 else if pname == ">" then
1432 v.ret(v.new_expr("{arguments[0]} > {arguments[1]}", ret.as(not null)))
1434 else if pname == "<=" then
1435 v.ret(v.new_expr("{arguments[0]} <= {arguments[1]}", ret.as(not null)))
1437 else if pname == ">=" then
1438 v.ret(v.new_expr("{arguments[0]} >= {arguments[1]}", ret.as(not null)))
1440 else if pname == "to_i" then
1441 v.ret(v.new_expr("(long){arguments[0]}", ret.as(not null)))
1444 else if cname == "Char" then
1445 if pname == "output" then
1446 v.add("printf(\"%c\", {arguments.first});")
1448 else if pname == "object_id" then
1449 v.ret(arguments.first)
1451 else if pname == "==" then
1452 v.ret(v.equal_test(arguments[0], arguments[1]))
1454 else if pname == "!=" then
1455 var res = v.equal_test(arguments[0], arguments[1])
1456 v.ret(v.new_expr("!{res}", 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 == "NativeString" then
1463 if pname == "[]" then
1464 v.ret(v.new_expr("{arguments[0]}[{arguments[1]}]", ret.as(not null)))
1466 else if pname == "[]=" then
1467 v.add("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1469 else if pname == "copy_to" then
1470 v.add("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1472 else if pname == "atoi" then
1473 v.ret(v.new_expr("atoi({arguments[0]});", ret.as(not null)))
1476 else if cname == "NativeArray" then
1477 v.native_array_def(pname, ret, arguments)
1480 if pname == "exit" then
1481 v.add("exit({arguments[1]});")
1483 else if pname == "sys" then
1484 v.ret(v.new_expr("glob_sys", ret.as(not null)))
1486 else if pname == "calloc_string" then
1487 v.ret(v.new_expr("(char*)GC_MALLOC_ATOMIC({arguments[1]})", ret.as(not null)))
1489 else if pname == "calloc_array" then
1490 v.calloc_array(ret.as(not null), arguments)
1492 else if pname == "object_id" then
1493 v.ret(v.new_expr("(long){arguments.first}", ret.as(not null)))
1495 else if pname == "is_same_type" then
1496 v.ret(v.is_same_type_test(arguments[0], arguments[1]))
1498 else if pname == "output_class_name" then
1499 var nat = v.class_name_string(arguments.first)
1500 v.add("printf(\"%s\\n\", {nat});")
1502 else if pname == "native_class_name" then
1503 var nat = v.class_name_string(arguments.first)
1504 v.ret(v.new_expr("(char*){nat}", ret.as(not null)))
1506 else if pname == "force_garbage_collection" then
1507 v.add("GC_gcollect();")
1510 v.add("printf(\"NOT YET IMPLEMENTED {class_name}:{mpropdef} at {location.to_s}\\n\");")
1511 debug("Not implemented {mpropdef}")
1515 redef class AExternMethPropdef
1516 redef fun compile_to_c(v, mpropdef, arguments)
1519 var nextern = self.n_extern
1520 if nextern == null then
1521 v.add("fprintf(stderr, \"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1525 externname = nextern.text.substring(1, nextern.text.length-2)
1526 if location.file != null then
1527 var file = location.file.filename
1528 v.compiler.add_extern(file)
1530 var res: nullable RuntimeVariable = null
1531 var ret = mpropdef.msignature.return_mtype
1533 ret = v.resolve_for(ret, arguments.first)
1534 res = v.new_var(ret)
1536 v.adapt_signature(mpropdef, arguments)
1539 v.add("{externname}({arguments.join(", ")});")
1541 v.add("{res} = {externname}({arguments.join(", ")});")
1547 redef class AExternInitPropdef
1548 redef fun compile_to_c(v, mpropdef, arguments)
1551 var nextern = self.n_extern
1552 if nextern == null then
1553 v.add("printf(\"NOT YET IMPLEMENTED nitni for {mpropdef} at {location.to_s}\\n\");")
1557 externname = nextern.text.substring(1, nextern.text.length-2)
1558 if location.file != null then
1559 var file = location.file.filename
1560 v.compiler.add_extern(file)
1562 v.adapt_signature(mpropdef, arguments)
1563 var ret = arguments.first.mtype
1564 var res = v.new_var(ret)
1568 v.add("{res} = {externname}({arguments.join(", ")});")
1573 redef class AAttrPropdef
1574 redef fun compile_to_c(v, mpropdef, arguments)
1576 if arguments.length == 1 then
1577 var res = v.read_attribute(self.mpropdef.mproperty, arguments.first)
1578 v.assign(v.frame.returnvar.as(not null), res)
1580 v.write_attribute(self.mpropdef.mproperty, arguments.first, arguments[1])
1584 fun init_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1586 var nexpr = self.n_expr
1587 if nexpr != null then
1588 var oldnode = v.current_node
1589 v.current_node = self
1590 var old_frame = v.frame
1591 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1593 var value = v.expr(nexpr, self.mpropdef.static_mtype)
1594 v.write_attribute(self.mpropdef.mproperty, recv, value)
1596 v.current_node = oldnode
1600 fun check_expr(v: AbstractCompilerVisitor, recv: RuntimeVariable)
1602 var nexpr = self.n_expr
1603 if nexpr != null then return
1605 var oldnode = v.current_node
1606 v.current_node = self
1607 var old_frame = v.frame
1608 var frame = new Frame(v, self.mpropdef.as(not null), recv.mtype.as(MClassType), [recv])
1610 # Force read to check the initialization
1611 v.read_attribute(self.mpropdef.mproperty, recv)
1613 v.current_node = oldnode
1617 redef class AClassdef
1618 private fun compile_to_c(v: AbstractCompilerVisitor, mpropdef: MMethodDef, arguments: Array[RuntimeVariable])
1620 if mpropdef == self.mfree_init then
1621 var super_inits = self.super_inits
1622 if super_inits != null then
1623 assert arguments.length == 1
1624 for su in super_inits do
1625 v.send(su, arguments)
1629 var recv = arguments.first
1631 # Collect undefined attributes
1632 for npropdef in self.n_propdefs do
1633 if npropdef isa AAttrPropdef and npropdef.n_expr == null then
1634 v.write_attribute(npropdef.mpropdef.mproperty, recv, arguments[i])
1644 redef class ADeferredMethPropdef
1645 redef fun compile_to_c(v, mpropdef, arguments) do v.add_abort("Deferred method called")
1646 redef fun can_inline do return true
1650 # Try to compile self as an expression
1651 # Do not call this method directly, use `v.expr' instead
1652 private fun expr
(v
: AbstractCompilerVisitor): nullable RuntimeVariable
1654 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
1655 var mtype
= self.mtype
1656 if mtype
== null then
1659 var res
= v
.new_var
(mtype
)
1660 v
.add
("/* {res} = NOT YET {class_name} */")
1665 # Try to compile self as a statement
1666 # Do not call this method directly, use `v.stmt' instead
1667 private fun stmt
(v
: AbstractCompilerVisitor)
1670 if res
!= null then v
.add
("{res};")
1674 redef class ABlockExpr
1677 for e
in self.n_expr
do v
.stmt
(e
)
1681 redef class AVardeclExpr
1684 var variable
= self.variable
.as(not null)
1685 var ne
= self.n_expr
1687 var i
= v
.expr
(ne
, variable
.declared_type
)
1688 v
.assign
(v
.variable
(variable
), i
)
1693 redef class AVarExpr
1696 var res
= v
.variable
(self.variable
.as(not null))
1697 var mtype
= self.mtype
.as(not null)
1698 return v
.autoadapt
(res
, mtype
)
1702 redef class AVarAssignExpr
1705 var variable
= self.variable
.as(not null)
1706 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1707 v
.assign
(v
.variable
(variable
), i
)
1711 redef class AVarReassignExpr
1714 var variable
= self.variable
.as(not null)
1715 var vari
= v
.variable
(variable
)
1716 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1717 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [vari
, value
])
1719 v
.assign
(v
.variable
(variable
), res
)
1723 redef class ASelfExpr
1724 redef fun expr
(v
) do return v
.frame
.arguments
.first
1727 redef class AContinueExpr
1728 redef fun stmt
(v
) do v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
1731 redef class ABreakExpr
1732 redef fun stmt
(v
) do v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
1735 redef class AReturnExpr
1738 var nexpr
= self.n_expr
1739 if nexpr
!= null then
1740 var returnvar
= v
.frame
.returnvar
.as(not null)
1741 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
1742 v
.assign
(returnvar
, i
)
1744 v
.add
("goto {v.frame.returnlabel.as(not null)};")
1748 redef class AAbortExpr
1749 redef fun stmt
(v
) do v
.add_abort
("Aborted")
1755 var cond
= v
.expr_bool
(self.n_expr
)
1756 v
.add
("if ({cond})\{")
1764 redef class AIfexprExpr
1767 var res
= v
.new_var
(self.mtype
.as(not null))
1768 var cond
= v
.expr_bool
(self.n_expr
)
1769 v
.add
("if ({cond})\{")
1770 v
.assign
(res
, v
.expr
(self.n_then
, null))
1772 v
.assign
(res
, v
.expr
(self.n_else
, null))
1781 v
.stmt
(self.n_block
)
1782 var escapemark
= self.escapemark
1783 if escapemark
!= null then
1784 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1789 redef class AWhileExpr
1793 var cond
= v
.expr_bool
(self.n_expr
)
1794 v
.add
("if (!{cond}) break;")
1795 v
.stmt
(self.n_block
)
1796 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1798 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1802 redef class ALoopExpr
1806 v
.stmt
(self.n_block
)
1807 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1809 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1813 redef class AForExpr
1816 # Shortcut on explicit range
1817 # Avoid the instantiation of the range and the iterator
1818 var nexpr
= self.n_expr
1819 if self.variables
.length
== 1 and nexpr
isa AOrangeExpr and not v
.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_range
.value
then
1820 var from
= v
.expr
(nexpr
.n_expr
, null)
1821 var to
= v
.expr
(nexpr
.n_expr2
, null)
1822 var variable
= v
.variable
(variables
.first
)
1824 v
.assign
(variable
, from
)
1825 v
.add
("for(;;) \{ /* shortcut range */")
1827 var ok
= v
.send
(v
.get_property
("<", variable
.mtype
), [variable
, to
])
1829 v
.add
("if(!{ok}) break;")
1831 v
.stmt
(self.n_block
)
1833 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1834 var succ
= v
.send
(v
.get_property
("succ", variable
.mtype
), [variable
])
1836 v
.assign
(variable
, succ
)
1838 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1842 var cl
= v
.expr
(self.n_expr
, null)
1843 var it_meth
= self.method_iterator
1844 assert it_meth
!= null
1845 var it
= v
.send
(it_meth
, [cl
])
1848 var isok_meth
= self.method_is_ok
1849 assert isok_meth
!= null
1850 var ok
= v
.send
(isok_meth
, [it
])
1852 v
.add
("if(!{ok}) break;")
1853 if self.variables
.length
== 1 then
1854 var item_meth
= self.method_item
1855 assert item_meth
!= null
1856 var i
= v
.send
(item_meth
, [it
])
1858 v
.assign
(v
.variable
(variables
.first
), i
)
1859 else if self.variables
.length
== 2 then
1860 var key_meth
= self.method_key
1861 assert key_meth
!= null
1862 var i
= v
.send
(key_meth
, [it
])
1864 v
.assign
(v
.variable
(variables
[0]), i
)
1865 var item_meth
= self.method_item
1866 assert item_meth
!= null
1867 i
= v
.send
(item_meth
, [it
])
1869 v
.assign
(v
.variable
(variables
[1]), i
)
1873 v
.stmt
(self.n_block
)
1874 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
1875 var next_meth
= self.method_next
1876 assert next_meth
!= null
1877 v
.send
(next_meth
, [it
])
1879 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
1883 redef class AAssertExpr
1886 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return
1888 var cond
= v
.expr_bool
(self.n_expr
)
1889 v
.add
("if (!{cond}) \{")
1893 v
.add_abort
("Assert '{nid.text}' failed")
1895 v
.add_abort
("Assert failed")
1904 var res
= v
.new_var
(self.mtype
.as(not null))
1905 var i1
= v
.expr_bool
(self.n_expr
)
1906 v
.add
("if ({i1}) \{")
1909 var i2
= v
.expr_bool
(self.n_expr2
)
1910 v
.add
("{res} = {i2};")
1916 redef class AAndExpr
1919 var res
= v
.new_var
(self.mtype
.as(not null))
1920 var i1
= v
.expr_bool
(self.n_expr
)
1921 v
.add
("if (!{i1}) \{")
1924 var i2
= v
.expr_bool
(self.n_expr2
)
1925 v
.add
("{res} = {i2};")
1931 redef class ANotExpr
1934 var cond
= v
.expr_bool
(self.n_expr
)
1935 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
1939 redef class AOrElseExpr
1942 var res
= v
.new_var
(self.mtype
.as(not null))
1943 var i1
= v
.expr
(self.n_expr
, null)
1944 v
.add
("if ({i1}!=NULL) \{")
1947 var i2
= v
.expr
(self.n_expr2
, null)
1957 var value1
= v
.expr
(self.n_expr
, null)
1958 var value2
= v
.expr
(self.n_expr2
, null)
1959 return v
.equal_test
(value1
, value2
)
1963 redef class AIntExpr
1964 redef fun expr
(v
) do return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
1967 redef class AFloatExpr
1968 redef fun expr
(v
) do return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
1971 redef class ACharExpr
1972 redef fun expr
(v
) do return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
1975 redef class AArrayExpr
1978 var mtype
= self.mtype
.as(MClassType).arguments
.first
1979 var array
= new Array[RuntimeVariable]
1980 for nexpr
in self.n_exprs
.n_exprs
do
1981 var i
= v
.expr
(nexpr
, mtype
)
1984 return v
.array_instance
(array
, mtype
)
1988 redef class AStringFormExpr
1989 redef fun expr
(v
) do return v
.string_instance
(self.value
.as(not null))
1992 redef class ASuperstringExpr
1995 var array
= new Array[RuntimeVariable]
1996 for ne
in self.n_exprs
do
1997 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
1998 var i
= v
.expr
(ne
, null)
2001 var a
= v
.array_instance
(array
, v
.object_type
)
2002 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2007 redef class ACrangeExpr
2010 var i1
= v
.expr
(self.n_expr
, null)
2011 var i2
= v
.expr
(self.n_expr2
, null)
2012 var mtype
= self.mtype
.as(MClassType)
2013 var res
= v
.init_instance
(mtype
)
2014 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2015 v
.check_init_instance
(res
, mtype
)
2020 redef class AOrangeExpr
2023 var i1
= v
.expr
(self.n_expr
, null)
2024 var i2
= v
.expr
(self.n_expr2
, null)
2025 var mtype
= self.mtype
.as(MClassType)
2026 var res
= v
.init_instance
(mtype
)
2027 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2028 v
.check_init_instance
(res
, mtype
)
2033 redef class ATrueExpr
2034 redef fun expr
(v
) do return v
.new_expr
("1", self.mtype
.as(not null))
2037 redef class AFalseExpr
2038 redef fun expr
(v
) do return v
.new_expr
("0", self.mtype
.as(not null))
2041 redef class ANullExpr
2042 redef fun expr
(v
) do return v
.new_expr
("NULL", self.mtype
.as(not null))
2045 redef class AIsaExpr
2048 var i
= v
.expr
(self.n_expr
, null)
2049 return v
.type_test
(i
, self.cast_type
.as(not null), "isa")
2053 redef class AAsCastExpr
2056 var i
= v
.expr
(self.n_expr
, null)
2057 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2059 var cond
= v
.type_test
(i
, self.mtype
.as(not null), "as")
2060 v
.add
("if (!{cond}) \{")
2061 v
.add_abort
("Cast failed")
2067 redef class AAsNotnullExpr
2070 var i
= v
.expr
(self.n_expr
, null)
2071 if v
.compiler
.modelbuilder
.toolcontext
.opt_no_check_assert
.value
then return i
2073 v
.add
("if ({i} == NULL) \{")
2074 v
.add_abort
("Cast failed")
2080 redef class AParExpr
2081 redef fun expr
(v
) do return v
.expr
(self.n_expr
, null)
2084 redef class AOnceExpr
2087 var mtype
= self.mtype
.as(not null)
2088 var name
= v
.get_name
("varonce")
2089 var guard
= v
.get_name
(name
+ "_guard")
2090 v
.add_decl
("static {mtype.ctype} {name};")
2091 v
.add_decl
("static int {guard};")
2092 var res
= v
.new_var
(mtype
)
2093 v
.add
("if ({guard}) \{")
2094 v
.add
("{res} = {name};")
2096 var i
= v
.expr
(self.n_expr
, mtype
)
2097 v
.add
("{res} = {i};")
2098 v
.add
("{name} = {res};")
2099 v
.add
("{guard} = 1;")
2105 redef class ASendExpr
2108 var recv
= v
.expr
(self.n_expr
, null)
2110 for a
in self.raw_arguments
.as(not null) do
2111 args
.add
(v
.expr
(a
, null))
2113 return v
.compile_callsite
(self.callsite
.as(not null), args
)
2117 redef class ASendReassignFormExpr
2120 var recv
= v
.expr
(self.n_expr
, null)
2122 for a
in self.raw_arguments
.as(not null) do
2123 args
.add
(v
.expr
(a
, null))
2125 var value
= v
.expr
(self.n_value
, null)
2127 var left
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2130 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [left
, value
])
2134 v
.compile_callsite
(self.write_callsite
.as(not null), args
)
2138 redef class ASuperExpr
2141 var recv
= v
.frame
.arguments
.first
2143 for a
in self.n_args
.n_exprs
do
2144 args
.add
(v
.expr
(a
, null))
2146 if args
.length
== 1 then
2147 args
= v
.frame
.arguments
2150 var mproperty
= self.mproperty
2151 if mproperty
!= null then
2152 if mproperty
.intro
.msignature
.arity
== 0 then
2156 var res
= v
.send
(mproperty
, args
)
2160 # stantard call-next-method
2161 return v
.supercall
(v
.frame
.mpropdef
.as(MMethodDef), recv
.mtype
.as(MClassType), args
)
2165 redef class ANewExpr
2168 var mtype
= self.mtype
.as(MClassType)
2170 var ctype
= mtype
.ctype
2171 if ctype
== "val*" then
2172 recv
= v
.init_instance
(mtype
)
2173 else if ctype
== "void*" then
2174 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2176 debug
("cannot new {mtype}")
2180 for a
in self.n_args
.n_exprs
do
2181 args
.add
(v
.expr
(a
, null))
2183 var res2
= v
.compile_callsite
(self.callsite
.as(not null), args
)
2184 if res2
!= null then
2185 #self.debug("got {res2} from {mproperty}. drop {recv}")
2188 v
.check_init_instance
(recv
, mtype
)
2193 redef class AAttrExpr
2196 var recv
= v
.expr
(self.n_expr
, null)
2197 var mproperty
= self.mproperty
.as(not null)
2198 return v
.read_attribute
(mproperty
, recv
)
2202 redef class AAttrAssignExpr
2205 var recv
= v
.expr
(self.n_expr
, null)
2206 var i
= v
.expr
(self.n_value
, null)
2207 var mproperty
= self.mproperty
.as(not null)
2208 v
.write_attribute
(mproperty
, recv
, i
)
2212 redef class AAttrReassignExpr
2215 var recv
= v
.expr
(self.n_expr
, null)
2216 var value
= v
.expr
(self.n_value
, null)
2217 var mproperty
= self.mproperty
.as(not null)
2218 var attr
= v
.read_attribute
(mproperty
, recv
)
2219 var res
= v
.compile_callsite
(self.reassign_callsite
.as(not null), [attr
, value
])
2221 v
.write_attribute
(mproperty
, recv
, res
)
2225 redef class AIssetAttrExpr
2228 var recv
= v
.expr
(self.n_expr
, null)
2229 var mproperty
= self.mproperty
.as(not null)
2230 return v
.isset_attribute
(mproperty
, recv
)
2234 redef class ADebugTypeExpr
2243 redef class HashSet[E
]
2244 init from
(elements
: Collection[E
]) do
2246 self.add_all
(elements
)
2250 redef class Array[E
]
2251 init from
(elements
: Collection[E
]) do
2253 self.add_all
(elements
)
2256 # Return a new Array with the elements only contened in 'self' and not in 'o'
2257 fun -(o
: Array[E
]): Array[E
] do
2258 var res
= new Array[E
]
2259 for e
in self do if not o
.has
(e
) then res
.add
(e
)
2266 # Return a linearization of a set of mtypes
2267 fun linearize_mtypes
(mtypes
: Set[MType]): Array[MType] do
2268 var lin
= new Array[MType].from
(mtypes
)
2269 var sorter
= new TypeSorter(self)
2274 # Return a reverse linearization of a set of mtypes
2275 fun reverse_linearize_mtypes
(mtypes
: Set[MType]): Array[MType] do
2276 var lin
= new Array[MType].from
(mtypes
)
2277 var sorter
= new ReverseTypeSorter(self)
2282 # Return super types of a `mtype` in `self`
2283 fun super_mtypes
(mtype
: MType, mtypes
: Set[MType]): Set[MType] do
2284 if not self.super_mtypes_cache
.has_key
(mtype
) then
2285 var supers
= new HashSet[MType]
2286 for otype
in mtypes
do
2287 if otype
== mtype
then continue
2288 if mtype
.is_subtype
(self, null, otype
) then
2292 self.super_mtypes_cache
[mtype
] = supers
2294 return self.super_mtypes_cache
[mtype
]
2297 private var super_mtypes_cache
: Map[MType, Set[MType]] = new HashMap[MType, Set[MType]]
2299 # Return all sub mtypes (directs and indirects) of a `mtype` in `self`
2300 fun sub_mtypes
(mtype
: MType, mtypes
: Set[MType]): Set[MType] do
2301 if not self.sub_mtypes_cache
.has_key
(mtype
) then
2302 var subs
= new HashSet[MType]
2303 for otype
in mtypes
do
2304 if otype
== mtype
then continue
2305 if otype
.is_subtype
(self, null, mtype
) then
2309 self.sub_mtypes_cache
[mtype
] = subs
2311 return self.sub_mtypes_cache
[mtype
]
2314 private var sub_mtypes_cache
: Map[MType, Set[MType]] = new HashMap[MType, Set[MType]]
2316 # Return a linearization of a set of mclasses
2317 fun linearize_mclasses_2
(mclasses
: Set[MClass]): Array[MClass] do
2318 var lin
= new Array[MClass].from
(mclasses
)
2319 var sorter
= new ClassSorter(self)
2324 # Return a reverse linearization of a set of mtypes
2325 fun reverse_linearize_mclasses
(mclasses
: Set[MClass]): Array[MClass] do
2326 var lin
= new Array[MClass].from
(mclasses
)
2327 var sorter
= new ReverseClassSorter(self)
2332 # Return all super mclasses (directs and indirects) of a `mclass` in `self`
2333 fun super_mclasses
(mclass
: MClass): Set[MClass] do
2334 if not self.super_mclasses_cache
.has_key
(mclass
) then
2335 var supers
= new HashSet[MClass]
2336 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2337 for sup
in self.flatten_mclass_hierarchy
[mclass
].greaters
do
2338 if sup
== mclass
then continue
2342 self.super_mclasses_cache
[mclass
] = supers
2344 return self.super_mclasses_cache
[mclass
]
2347 private var super_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2349 # Return all parents of a `mclass` in `self`
2350 fun parent_mclasses
(mclass
: MClass): Set[MClass] do
2351 if not self.parent_mclasses_cache
.has_key
(mclass
) then
2352 var parents
= new HashSet[MClass]
2353 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2354 for sup
in self.flatten_mclass_hierarchy
[mclass
].direct_greaters
do
2355 if sup
== mclass
then continue
2359 self.parent_mclasses_cache
[mclass
] = parents
2361 return self.parent_mclasses_cache
[mclass
]
2364 private var parent_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2366 # Return all sub mclasses (directs and indirects) of a `mclass` in `self`
2367 fun sub_mclasses
(mclass
: MClass): Set[MClass] do
2368 if not self.sub_mclasses_cache
.has_key
(mclass
) then
2369 var subs
= new HashSet[MClass]
2370 if self.flatten_mclass_hierarchy
.has
(mclass
) then
2371 for sub
in self.flatten_mclass_hierarchy
[mclass
].smallers
do
2372 if sub
== mclass
then continue
2376 self.sub_mclasses_cache
[mclass
] = subs
2378 return self.sub_mclasses_cache
[mclass
]
2381 private var sub_mclasses_cache
: Map[MClass, Set[MClass]] = new HashMap[MClass, Set[MClass]]
2383 # All 'mproperties' associated to all 'mclassdefs' of `mclass`
2384 fun properties
(mclass
: MClass): Set[MProperty] do
2385 if not self.properties_cache
.has_key
(mclass
) then
2386 var properties
= new HashSet[MProperty]
2387 var parents
= self.super_mclasses
(mclass
)
2388 for parent
in parents
do
2389 properties
.add_all
(self.properties
(parent
))
2392 for mclassdef
in mclass
.mclassdefs
do
2393 for mpropdef
in mclassdef
.mpropdefs
do
2394 properties
.add
(mpropdef
.mproperty
)
2397 self.properties_cache
[mclass
] = properties
2399 return properties_cache
[mclass
]
2402 private var properties_cache
: Map[MClass, Set[MProperty]] = new HashMap[MClass, Set[MProperty]]
2405 # A sorter for linearize list of types
2406 private class TypeSorter
2407 super AbstractSorter[MType]
2409 private var mmodule
: MModule
2411 init(mmodule
: MModule) do self.mmodule
= mmodule
2413 redef fun compare
(a
, b
) do
2416 else if a
.is_subtype
(self.mmodule
, null, b
) then
2423 # A sorter for reverse linearization
2424 private class ReverseTypeSorter
2427 init(mmodule
: MModule) do end
2429 redef fun compare
(a
, b
) do
2432 else if a
.is_subtype
(self.mmodule
, null, b
) then
2439 # A sorter for linearize list of classes
2440 private class ClassSorter
2441 super AbstractSorter[MClass]
2443 var mmodule
: MModule
2445 redef fun compare
(a
, b
) do
2448 else if self.mmodule
.flatten_mclass_hierarchy
.has
(a
) and self.mmodule
.flatten_mclass_hierarchy
[a
].greaters
.has
(b
) then
2455 # A sorter for reverse linearization
2456 private class ReverseClassSorter
2457 super AbstractSorter[MClass]
2459 var mmodule
: MModule
2461 redef fun compare
(a
, b
) do
2464 else if self.mmodule
.flatten_mclass_hierarchy
.has
(a
) and self.mmodule
.flatten_mclass_hierarchy
[a
].greaters
.has
(b
) then