1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Separate compilation of a Nit program
16 module separate_compiler
19 import global_compiler
# TODO better separation of concerns
20 intrude import coloring
21 redef class ToolContext
23 var opt_separate
: OptionBool = new OptionBool("Use separate compilation", "--separate")
28 self.option_context
.add_option
(self.opt_separate
)
32 redef class ModelBuilder
33 redef fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
35 # Hijack the run_global_compiler to run the separate one if requested.
36 if self.toolcontext
.opt_separate
.value
then
37 run_separate_compiler
(mainmodule
, runtime_type_analysis
)
43 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
46 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
48 var compiler
= new SeparateCompiler(mainmodule
, runtime_type_analysis
, self)
49 var v
= new SeparateCompilerVisitor(compiler
)
51 v
.add_decl
("#include <stdlib.h>")
52 v
.add_decl
("#include <stdio.h>")
53 v
.add_decl
("#include <string.h>")
54 v
.add_decl
("#include <gc/gc.h>")
55 v
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
56 v
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
58 # Class abstract representation
59 v
.add_decl
("struct class \{ nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
60 # Type abstract representation
61 v
.add_decl
("struct type \{ int id; int color; struct fts_table *fts_table; int type_table[1]; \}; /* general C type representing a Nit type. */")
62 v
.add_decl
("struct fts_table \{ struct type *fts[1]; \}; /* fts list of a C type representation. */")
63 # Instance abstract representation
64 v
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
67 # The main function of the C
69 v
= new SeparateCompilerVisitor(compiler
)
70 v
.add_decl
("int glob_argc;")
71 v
.add_decl
("char **glob_argv;")
72 v
.add_decl
("val *glob_sys;")
73 v
.add_decl
("int main(int argc, char** argv) \{")
74 v
.add
("glob_argc = argc; glob_argv = argv;")
75 var main_type
= mainmodule
.sys_type
76 if main_type
== null then return # Nothing to compile
77 var glob_sys
= v
.init_instance
(main_type
)
78 v
.add
("glob_sys = {glob_sys};")
79 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
80 if main_init
!= null then
81 v
.send
(main_init
, [glob_sys
])
83 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
84 if main_method
!= null then
85 v
.send
(main_method
, [glob_sys
])
89 # compile class structures
90 for m
in mainmodule
.in_importation
.greaters
do
91 for mclass
in m
.intro_mclasses
do
92 compiler
.compile_class_to_c
(mclass
)
97 for m
in mainmodule
.in_importation
.greaters
do
98 compiler
.compile_module_to_c
(m
)
101 # compile live & cast type structures
102 var mtypes
= compiler
.do_global_type_coloring
104 compiler
.compile_type_to_c
(t
)
107 # compile live generic types selection structures
108 for mclass
in model
.mclasses
do
109 compiler
.compile_live_gentype_to_c
(mclass
)
112 # for the class_name and output_class_name methods
113 compiler
.compile_class_names
115 write_and_make
(compiler
)
119 # Singleton that store the knowledge about the separate compilation process
120 class SeparateCompiler
121 super GlobalCompiler # TODO better separation of concerns
123 private var undead_types
: Set[MClassType] = new HashSet[MClassType]
124 protected var typeids
: HashMap[MClassType, Int] = new HashMap[MClassType, Int]
126 private var type_colors
: Map[MClassType, Int] = typeids
127 private var type_tables
: nullable Map[MClassType, Array[nullable MClassType]] = null
128 private var livetypes_tables
: nullable Map[MClass, Array[nullable Object]]
129 private var livetypes_tables_sizes
: nullable Map[MClass, Array[Int]]
131 private var class_colors
: Map[MClass, Int]
133 private var method_colors
: Map[MMethod, Int]
134 private var method_tables
: Map[MClass, Array[nullable MMethodDef]]
136 private var attr_colors
: Map[MAttribute, Int]
137 private var attr_tables
: Map[MClass, Array[nullable MAttributeDef]]
139 private var ft_colors
: Map[MParameterType, Int]
140 private var ft_tables
: Map[MClass, Array[nullable MParameterType]]
142 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
144 var class_coloring
= new ClassColoring(mainmodule
)
145 self.class_colors
= class_coloring
.colorize
(mmbuilder
.model
.mclasses
)
148 var method_coloring
= new MethodColoring(class_coloring
)
149 self.method_colors
= method_coloring
.colorize
150 self.method_tables
= method_coloring
.build_property_tables
152 # attributes coloration
153 var attribute_coloring
= new AttributeColoring(class_coloring
)
154 self.attr_colors
= attribute_coloring
.colorize
155 self.attr_tables
= attribute_coloring
.build_property_tables
158 var ft_coloring
= new FTColoring(class_coloring
)
159 self.ft_colors
= ft_coloring
.colorize
160 self.ft_tables
= ft_coloring
.build_ft_tables
163 private fun compile_class_names
do
165 # Build type names table
166 var type_array
= new Array[nullable MClassType]
167 for t
, i
in typeids
do
168 if i
>= type_array
.length
then
174 var v
= new SeparateCompilerVisitor(self)
175 self.header
.add_decl
("extern const char const * class_names[];")
176 v
.add
("const char const * class_names[] = \{")
177 for t
in type_array
do
187 # colorize live types of the program
188 private fun do_global_type_coloring
: Set[MClassType] do
189 var mtypes
= new HashSet[MClassType]
190 #print "undead types:"
191 #for t in self.undead_types do
195 #for t in runtime_type_analysis.live_types do
199 #for t in runtime_type_analysis.live_cast_types do
203 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
204 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
205 mtypes
.add_all
(self.undead_types
)
207 # add formal types arguments to mtypes
208 for mtype
in mtypes
do
209 if mtype
isa MGenericType then
210 #TODO do it recursive
211 for ft
in mtype
.arguments
do
212 if ft
isa MNullableType then ft
= ft
.mtype
213 mtypes
.add
(ft
.as(MClassType))
219 for mtype
in mtypes
do
220 self.typeids
[mtype
] = self.typeids
.length
223 # build livetypes tables
224 self.livetypes_tables
= new HashMap[MClass, Array[nullable Object]]
225 self.livetypes_tables_sizes
= new HashMap[MClass, Array[Int]]
226 for mtype
in mtypes
do
227 if mtype
isa MGenericType then
228 var table
: Array[nullable Object]
229 var sizes
: Array[Int]
230 if livetypes_tables
.has_key
(mtype
.mclass
) then
231 table
= livetypes_tables
[mtype
.mclass
]
233 table
= new Array[nullable Object]
234 self.livetypes_tables
[mtype
.mclass
] = table
236 if livetypes_tables_sizes
.has_key
(mtype
.mclass
) then
237 sizes
= livetypes_tables_sizes
[mtype
.mclass
]
239 sizes
= new Array[Int]
240 self.livetypes_tables_sizes
[mtype
.mclass
] = sizes
242 build_livetype_table
(mtype
, 0, table
, sizes
)
247 var type_coloring
= new TypeColoring(self.mainmodule
, self.runtime_type_analysis
)
248 self.type_colors
= type_coloring
.colorize
(mtypes
)
249 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
254 # build live gentype table recursively
255 private fun build_livetype_table
(mtype
: MGenericType, current_rank
: Int, table
: Array[nullable Object], sizes
: Array[Int]) do
256 var ft
= mtype
.arguments
[current_rank
]
257 if ft
isa MNullableType then ft
= ft
.mtype
258 var id
= self.typeids
[ft
.as(MClassType)]
260 if current_rank
>= sizes
.length
then
261 sizes
[current_rank
] = id
+ 1
262 else if id
>= sizes
[current_rank
] then
263 sizes
[current_rank
] = id
+ 1
266 if id
> table
.length
then
267 for i
in [table
.length
.. id
[ do table
[i
] = null
270 if current_rank
== mtype
.arguments
.length
- 1 then
273 var ft_table
= new Array[nullable Object]
275 build_livetype_table
(mtype
, current_rank
+ 1, ft_table
, sizes
)
279 private fun add_to_livetypes_table
(table
: Array[nullable Object], ft
: MClassType) do
280 var id
= self.typeids
[ft
]
281 for i
in [table
.length
.. id
[ do
287 private fun compile_livetype_table
(table
: Array[nullable Object], buffer
: Buffer, depth
: Int, max
: Int) do
291 buffer
.append
("NULL,\n")
293 buffer
.append
("\{\},\n")
295 else if obj
isa MClassType then
296 buffer
.append
("(struct type*) &type_{obj.c_name}, /* {obj} */\n")
297 else if obj
isa Array[nullable Object] then
298 buffer
.append
("\{\n")
299 compile_livetype_table
(obj
, buffer
, depth
+ 1, max
)
300 buffer
.append
("\},\n")
305 # declare live generic types tables selection
306 private fun compile_live_gentype_to_c
(mclass
: MClass) do
307 if mclass
.arity
> 0 then
308 if self.livetypes_tables
.has_key
(mclass
) then
309 var table
= self.livetypes_tables
[mclass
]
310 var sign
= self.livetypes_tables_sizes
[mclass
]
311 var table_buffer
= new Buffer.from
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}] = \{\n")
312 compile_livetype_table
(table
, table_buffer
, 1, mclass
.arity
)
313 table_buffer
.append
("\};")
315 var v
= new SeparateCompilerVisitor(self)
316 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
317 v
.add_decl
(table_buffer
.to_s
)
319 var sign
= new Array[Int].filled_with
(0, mclass
.arity
)
320 var v
= new SeparateCompilerVisitor(self)
321 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
322 v
.add_decl
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
327 # Separately compile all the method definitions of the module
328 fun compile_module_to_c
(mmodule
: MModule)
330 for cd
in mmodule
.mclassdefs
do
331 for pd
in cd
.mpropdefs
do
332 if not pd
isa MMethodDef then continue
333 #print "compile {pd} @ {cd} @ {mmodule}"
334 var r
= new SeparateRuntimeFunction(pd
)
336 if true or cd
.bound_mtype
.ctype
!= "val*" then
337 var r2
= new VirtualRuntimeFunction(pd
)
338 r2
.compile_to_c
(self)
344 # Globaly compile the type structure of a live type
345 fun compile_type_to_c
(mtype
: MClassType)
347 var c_name
= mtype
.c_name
348 var v
= new SeparateCompilerVisitor(self)
349 v
.add_decl
("/* runtime type {mtype} */")
351 # extern const struct type_X
352 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
353 self.header
.add_decl
("struct type_{c_name} \{")
354 self.header
.add_decl
("int id;")
355 self.header
.add_decl
("int color;")
356 self.header
.add_decl
("const struct fts_table_{c_name} *fts_table;")
357 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
358 self.header
.add_decl
("\};")
360 # extern const struct fst_table_X fst_table_X
361 self.header
.add_decl
("extern const struct fts_table_{c_name} fts_table_{c_name};")
362 self.header
.add_decl
("struct fts_table_{c_name} \{")
363 self.header
.add_decl
("struct type *fts[{self.ft_tables[mtype.mclass].length}];")
364 self.header
.add_decl
("\};")
366 # const struct type_X
367 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
368 v
.add_decl
("{self.typeids[mtype]},")
369 v
.add_decl
("{self.type_colors[mtype]},")
370 v
.add_decl
("&fts_table_{c_name},")
372 for stype
in self.type_tables
[mtype
] do
373 if stype
== null then
374 v
.add_decl
("-1, /* empty */")
376 v
.add_decl
("{self.typeids[stype]}, /* {stype} */")
382 # const struct fst_table_X fst_table_X
383 v
.add_decl
("const struct fts_table_{c_name} fts_table_{c_name} = \{")
386 for ft
in self.ft_tables
[mtype
.mclass
] do
388 v
.add_decl
("NULL, /* empty */")
392 if ft
.mclass
== mtype
.mclass
then
393 ntype
= mtype
.arguments
[ft
.rank
]
395 ntype
= ft
.anchor_to
(self.mainmodule
, mtype
)
397 if ntype
isa MNullableType then ntype
= ntype
.mtype
398 var ftype
= ntype
.as(MClassType)
399 if self.typeids
.has_key
(ftype
) then
400 v
.add_decl
("(struct type*)&type_{ftype.c_name}, /* {ft} ({ftype}) */")
402 v
.add_decl
("NULL, /* empty ({ft} not a live type) */")
411 # Globally compile the table of the class mclass
412 # In a link-time optimisation compiler, tables are globally computed
413 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
414 fun compile_class_to_c
(mclass
: MClass)
416 var mtype
= mclass
.intro
.bound_mtype
417 var c_name
= mclass
.c_name
419 var vft
= self.method_tables
[mclass
]
420 var attrs
= self.attr_tables
[mclass
]
421 var v
= new SeparateCompilerVisitor(self)
423 v
.add_decl
("/* runtime class {c_name} */")
424 var idnum
= classids
.length
425 var idname
= "ID_" + c_name
426 self.classids
[mtype
] = idname
427 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
429 self.header
.add_decl
("struct class_{c_name} \{")
430 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
432 if mtype
.ctype
!= "val*" then
433 # Is the Nit type is native then the struct is a box with two fields:
434 # * the `vft` to be polymorph
435 # * the `value` that contains the native value.
436 self.header
.add_decl
("{mtype.ctype} value;")
439 # Collect all attributes and associate them a field in the structure.
440 # Note: we do not try to optimize the order and helps CC to optimize the client code.
441 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
442 for p
in cd
.intro_mproperties
do
443 if not p
isa MAttribute then continue
444 var t
= p
.intro
.static_mtype
.as(not null)
445 t
= t
.anchor_to
(self.mainmodule
, mtype
)
446 self.header
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
449 self.header
.add_decl
("\};")
452 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
453 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
455 for i
in [0 .. vft
.length
[ do
456 var mpropdef
= vft
[i
]
457 if mpropdef
== null then
458 v
.add_decl
("NULL, /* empty */")
460 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
461 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
463 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
470 if mtype
.ctype
!= "val*" then
471 #Build instance struct
472 self.header
.add_decl
("struct instance_{c_name} \{")
473 self.header
.add_decl
("const struct type *type;")
474 self.header
.add_decl
("const struct class *class;")
475 self.header
.add_decl
("{mtype.ctype} value;")
476 self.header
.add_decl
("\};")
478 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype}, struct type*);")
479 v
.add_decl
("/* allocate {mtype} */")
480 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value, struct type* type) \{")
481 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
482 v
.add
("res->type = type;")
483 v
.add
("res->class = (struct class*) &class_{c_name};")
484 v
.add
("res->value = value;")
485 v
.add
("return (val*)res;")
490 var is_native_array
= mclass
.name
== "NativeArray"
493 if is_native_array
then
494 sig
= "int length, struct type* type"
496 sig
= "struct type* type"
499 #Build instance struct
500 #extern const struct instance_array__NativeArray instance_array__NativeArray;
501 self.header
.add_decl
("struct instance_{c_name} \{")
502 self.header
.add_decl
("const struct type *type;")
503 self.header
.add_decl
("const struct class *class;")
504 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
505 if is_native_array
then
506 # NativeArrays are just a instance header followed by an array of values
507 self.header
.add_decl
("val* values[0];")
509 self.header
.add_decl
("\};")
512 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
513 v
.add_decl
("/* allocate {mtype} */")
514 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
515 var res
= v
.new_named_var
(mtype
, "self")
517 if is_native_array
then
518 var mtype_elt
= mtype
.arguments
.first
519 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
521 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
523 #v.add("{res} = calloc(sizeof(struct instance_{c_name}), 1);")
524 v
.add
("{res}->type = type;")
525 v
.add
("{res}->class = (struct class*) &class_{c_name};")
527 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
529 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
530 for npropdef
in n
.n_propdefs
do
531 if npropdef
isa AAttrPropdef then
532 npropdef
.init_expr
(v
, res
)
536 v
.add
("return {res};")
541 # The C function associated to a methoddef separately compiled
542 class SeparateRuntimeFunction
543 super AbstractRuntimeFunction
545 redef fun build_c_name
: String
547 return "{mmethoddef.c_name}"
550 redef fun to_s
do return self.mmethoddef
.to_s
552 redef fun compile_to_c
(compiler
)
554 var mmethoddef
= self.mmethoddef
556 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
557 var v
= new SeparateCompilerVisitor(compiler
)
558 var selfvar
= new RuntimeVariable("self", recv
, recv
)
559 var arguments
= new Array[RuntimeVariable]
560 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
564 var comment
= new Buffer
565 var ret
= mmethoddef
.msignature
.return_mtype
567 ret
= v
.resolve_for
(ret
, selfvar
)
568 sig
.append
("{ret.ctype} ")
569 else if mmethoddef
.mproperty
.is_new
then
571 sig
.append
("{ret.ctype} ")
575 sig
.append
(self.c_name
)
576 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
577 comment
.append
("(self: {selfvar}")
578 arguments
.add
(selfvar
)
579 for i
in [0..mmethoddef
.msignature
.arity
[ do
580 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
581 if i
== mmethoddef
.msignature
.vararg_rank
then
582 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
584 mtype
= v
.resolve_for
(mtype
, selfvar
)
585 comment
.append
(", {mtype}")
586 sig
.append
(", {mtype.ctype} p{i}")
587 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
588 arguments
.add
(argvar
)
593 comment
.append
(": {ret}")
595 compiler
.header
.add_decl
("{sig};")
597 v
.add_decl
("/* method {self} for {comment} */")
598 v
.add_decl
("{sig} \{")
600 frame
.returnvar
= v
.new_var
(ret
)
602 frame
.returnlabel
= v
.get_name
("RET_LABEL")
604 if recv
!= arguments
.first
.mtype
then
605 #print "{self} {recv} {arguments.first}"
607 mmethoddef
.compile_inside_to_c
(v
, arguments
)
609 v
.add
("{frame.returnlabel.as(not null)}:;")
611 v
.add
("return {frame.returnvar.as(not null)};")
617 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
618 # The first parameter (the reciever) is always typed by val* in order to accept an object value
619 class VirtualRuntimeFunction
620 super AbstractRuntimeFunction
622 redef fun build_c_name
: String
624 return "VIRTUAL_{mmethoddef.c_name}"
627 redef fun to_s
do return self.mmethoddef
.to_s
629 redef fun compile_to_c
(compiler
)
631 var mmethoddef
= self.mmethoddef
633 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
634 var v
= new SeparateCompilerVisitor(compiler
)
635 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
636 var arguments
= new Array[RuntimeVariable]
637 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
641 var comment
= new Buffer
643 # Because the function is virtual, the signature must match the one of the original class
644 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
645 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
646 var ret
= msignature
.return_mtype
648 sig
.append
("{ret.ctype} ")
649 else if mmethoddef
.mproperty
.is_new
then
651 sig
.append
("{ret.ctype} ")
655 sig
.append
(self.c_name
)
656 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
657 comment
.append
("(self: {selfvar}")
658 arguments
.add
(selfvar
)
659 for i
in [0..msignature
.arity
[ do
660 var mtype
= msignature
.mparameters
[i
].mtype
661 if i
== msignature
.vararg_rank
then
662 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
664 comment
.append
(", {mtype}")
665 sig
.append
(", {mtype.ctype} p{i}")
666 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
667 arguments
.add
(argvar
)
672 comment
.append
(": {ret}")
674 compiler
.header
.add_decl
("{sig};")
676 v
.add_decl
("/* method {self} for {comment} */")
677 v
.add_decl
("{sig} \{")
679 frame
.returnvar
= v
.new_var
(ret
)
681 frame
.returnlabel
= v
.get_name
("RET_LABEL")
683 if recv
!= arguments
.first
.mtype
then
684 #print "{self} {recv} {arguments.first}"
686 mmethoddef
.compile_inside_to_c
(v
, arguments
)
688 v
.add
("{frame.returnlabel.as(not null)}:;")
690 v
.add
("return {frame.returnvar.as(not null)};")
695 redef fun call
(v
, arguments
)
702 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
703 class SeparateCompilerVisitor
704 super GlobalCompilerVisitor # TODO better separation of concerns
706 redef fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
708 var recv
= args
.first
709 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
710 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
712 for i
in [0..m
.msignature
.arity
[ do
713 var t
= m
.msignature
.mparameters
[i
].mtype
714 if i
== m
.msignature
.vararg_rank
then
717 t
= self.resolve_for
(t
, recv
)
718 args
[i
+1] = self.autobox
(args
[i
+1], t
)
722 # Box or unbox a value to another type iff a C type conversion is needed
723 # ENSURE: result.mtype.ctype == mtype.ctype
724 redef fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
726 if value
.mtype
.ctype
== mtype
.ctype
then
728 else if value
.mtype
.ctype
== "val*" then
729 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
730 else if mtype
.ctype
== "val*" then
731 var valtype
= value
.mtype
.as(MClassType)
732 var res
= self.new_var
(mtype
)
733 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
734 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
735 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
738 var totype
= value
.mtype
739 if totype
isa MNullableType then totype
= totype
.mtype
740 self.add
("{res} = BOX_{valtype.c_name}({value}, (struct type*) &type_{totype.c_name}); /* autobox from {value.mtype} to {mtype} */")
743 # Bad things will appen!
744 var res
= self.new_var
(mtype
)
745 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
746 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
751 redef fun send
(mmethod
, arguments
)
753 if arguments
.first
.mtype
.ctype
!= "val*" then
754 assert arguments
.first
.mtype
== arguments
.first
.mcasttype
755 return self.monomorphic_send
(mmethod
, arguments
.first
.mtype
, arguments
)
758 var res
: nullable RuntimeVariable
759 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
760 var ret
= msignature
.return_mtype
761 if mmethod
.is_new
then
762 ret
= arguments
.first
.mtype
763 res
= self.new_var
(ret
)
764 else if ret
== null then
767 ret
= self.resolve_for
(ret
, arguments
.first
)
768 res
= self.new_var
(ret
)
774 var recv
= arguments
.first
777 for i
in [0..msignature
.arity
[ do
778 var a
= arguments
[i
+1]
779 var t
= msignature
.mparameters
[i
].mtype
780 s
.append
(", {t.ctype}")
781 a
= self.autobox
(a
, t
)
785 var maybenull
= recv
.mcasttype
isa MNullableType
787 self.add
("if ({recv} == NULL) \{")
788 if mmethod
.name
== "==" then
790 var arg
= arguments
[1]
791 if arg
.mcasttype
isa MNullableType then
792 self.add
("{res} = ({arg} == NULL);")
793 else if arg
.mcasttype
isa MNullType then
794 self.add
("{res} = 1; /* is null */")
796 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
798 else if mmethod
.name
== "!=" then
800 var arg
= arguments
[1]
801 if arg
.mcasttype
isa MNullableType then
802 self.add
("{res} = ({arg} != NULL);")
803 else if arg
.mcasttype
isa MNullType then
804 self.add
("{res} = 0; /* is null */")
806 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
809 self.add_abort
("Reciever is null")
811 self.add
("\} else \{")
814 var color
= self.compiler
.as(SeparateCompiler).method_colors
[mmethod
]
816 if ret
== null then r
= "void" else r
= ret
.ctype
817 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
820 self.add
("{res} = {call};")
832 redef fun call
(mmethoddef
, recvtype
, arguments
)
834 var res
: nullable RuntimeVariable
835 var ret
= mmethoddef
.msignature
.return_mtype
836 if mmethoddef
.mproperty
.is_new
then
837 ret
= arguments
.first
.mtype
838 res
= self.new_var
(ret
)
839 else if ret
== null then
842 ret
= self.resolve_for
(ret
, arguments
.first
)
843 res
= self.new_var
(ret
)
847 self.adapt_signature
(mmethoddef
, arguments
)
850 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
853 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
859 redef fun isset_attribute
(a
, recv
)
861 # FIXME: Here we inconditionally return boxed primitive attributes
862 var res
= self.new_var
(bool_type
)
863 self.add
("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}] != NULL; /* {a} on {recv.inspect}*/")
867 redef fun read_attribute
(a
, recv
)
869 # FIXME: Here we inconditionally return boxed primitive attributes
870 var ret
= a
.intro
.static_mtype
.as(not null)
871 ret
= self.resolve_for
(ret
, recv
)
872 var cret
= self.object_type
.as_nullable
873 var res
= self.new_var
(cret
)
875 self.add
("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}]; /* {a} on {recv.inspect} */")
876 if not ret
isa MNullableType then
877 self.add
("if ({res} == NULL) \{")
878 self.add_abort
("Uninitialized attribute {a.name}")
885 redef fun write_attribute
(a
, recv
, value
)
887 # FIXME: Here we inconditionally box primitive attributes
888 value
= self.autobox
(value
, self.object_type
.as_nullable
)
889 self.add
("{recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}] = {value}; /* {a} on {recv.inspect} */")
892 redef fun init_instance
(mtype
)
894 var compiler
= self.compiler
.as(SeparateCompiler)
895 if mtype
isa MGenericType and mtype
.need_anchor
then
896 var buff
= new Buffer
898 for ft
in mtype
.arguments
do
899 if ft
isa MParameterType then
900 var ftcolor
= compiler
.ft_colors
[ft
]
901 buff
.append
("[self->type->fts_table->fts[{ftcolor}]->id]")
902 else if ft
isa MGenericType and ft
.need_anchor
then
903 var ft_decl
= mtype
.mclass
.mclass_type
.arguments
[rank
]
904 var ftcolor
= compiler
.ft_colors
[ft_decl
.as(MParameterType)]
905 buff
.append
("[self->type->fts_table->fts[{ftcolor}]->id]")
907 var typecolor
= compiler
.type_colors
[ft
.as(MClassType)]
908 buff
.append
("[{typecolor}]")
912 mtype
= self.anchor
(mtype
).as(MClassType)
913 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
915 compiler
.undead_types
.add
(mtype
)
916 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
919 redef fun type_test
(value
, mtype
)
921 var compiler
= self.compiler
.as(SeparateCompiler)
922 var res
= self.new_var
(bool_type
)
923 var buff
= new Buffer
926 if mtype
isa MNullableType then
928 s
= "{value} == NULL ||"
930 s
= "{value} != NULL &&"
932 if mtype
isa MGenericType and mtype
.need_anchor
then
933 for ft
in mtype
.mclass
.mclass_type
.arguments
do
934 var ftcolor
= compiler
.ft_colors
[ft
.as(MParameterType)]
935 buff
.append
("[self->type->fts_table->fts[{ftcolor}]->id]")
937 self.add
("{res} = {s} {value}->type->type_table[livetypes_{mtype.mclass.c_name}{buff.to_s}->color] == livetypes_{mtype.mclass.c_name}{buff.to_s}->id;")
938 else if mtype
isa MClassType then
939 compiler
.undead_types
.add
(mtype
)
940 self.add
("{res} = {s} {value}->type->type_table[type_{mtype.c_name}.color] == type_{mtype.c_name}.id;")
941 else if mtype
isa MParameterType then
942 var ftcolor
= compiler
.ft_colors
[mtype
]
943 self.add
("{res} = {s} {value}->type->type_table[self->type->fts_table->fts[{ftcolor}]->color] == self->type->fts_table->fts[{ftcolor}]->id;")
945 add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
951 redef fun is_same_type_test
(value1
, value2
)
953 var res
= self.new_var
(bool_type
)
954 # Swap values to be symetric
955 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
960 if value1
.mtype
.ctype
!= "val*" then
961 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
962 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
963 else if value2
.mtype
.ctype
!= "val*" then
964 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
966 var mtype1
= value1
.mtype
.as(MClassType)
967 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
970 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
975 redef fun class_name_string
(value1
)
977 var res
= self.get_name
("var_class_name")
978 self.add_decl
("const char* {res} = class_names[self->type->id];")
982 redef fun equal_test
(value1
, value2
)
984 var res
= self.new_var
(bool_type
)
985 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
990 if value1
.mtype
.ctype
!= "val*" then
991 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
992 self.add
("{res} = {value1} == {value2};")
993 else if value2
.mtype
.ctype
!= "val*" then
994 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
996 var mtype1
= value1
.mtype
.as(MClassType)
997 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
998 self.add
("if ({res}) \{")
999 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1003 var s
= new Array[String]
1004 # This is just ugly on so many level. this works but must be rewriten
1005 for t
in self.compiler
.live_primitive_types
do
1006 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1007 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1008 s
.add
"({value1}->class == (struct class*)&class_{t.c_name} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1011 self.add
("{res} = {value1} == {value2};")
1013 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class && ({s.join(" || ")}));")
1019 redef fun array_instance
(array
, elttype
)
1021 var compiler
= self.compiler
.as(SeparateCompiler)
1022 var nclass
= self.get_class
("NativeArray")
1023 elttype
= self.anchor
(elttype
)
1024 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
1025 var res
= self.init_instance
(arraytype
)
1026 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1027 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1029 compiler
.undead_types
.add
(nat
.mtype
.as(MClassType))
1030 self.add
("{nat} = NEW_{nclass.c_name}({array.length}, (struct type *) &type_{nat.mtype.c_name});")
1031 for i
in [0..array
.length
[ do
1032 var r
= self.autobox
(array
[i
], self.object_type
)
1033 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1035 var length
= self.int_instance
(array
.length
)
1036 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1037 self.check_init_instance
(res
)
1042 redef fun native_array_def
(pname
, ret_type
, arguments
)
1044 var elttype
= arguments
.first
.mtype
1045 var nclass
= self.get_class
("NativeArray")
1046 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1047 if pname
== "[]" then
1048 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1050 else if pname
== "[]=" then
1051 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1053 else if pname
== "copy_to" then
1054 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1055 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1060 redef fun calloc_array
(ret_type
, arguments
)
1062 var ret
= ret_type
.as(MClassType)
1063 var compiler
= self.compiler
.as(SeparateCompiler)
1064 compiler
.undead_types
.add
(ret
)
1065 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]}, (struct type*) &type_{ret_type.c_name})", ret_type
))
1070 # Return the name of the C structure associated to a Nit class
1071 fun c_name
: String do
1072 var res
= self.c_name_cache
1073 if res
!= null then return res
1074 res
= "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1075 self.c_name_cache
= res
1078 private var c_name_cache
: nullable String