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 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
36 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
38 var compiler
= new SeparateCompiler(mainmodule
, runtime_type_analysis
, self)
39 var v
= compiler
.new_visitor
41 v
.add_decl
("#include <stdlib.h>")
42 v
.add_decl
("#include <stdio.h>")
43 v
.add_decl
("#include <string.h>")
44 v
.add_decl
("#include <gc/gc.h>")
45 v
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
46 v
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
48 # Class abstract representation
49 v
.add_decl
("struct class \{ nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
50 # Type abstract representation
51 v
.add_decl
("struct type \{ int id; int color; int livecolor; short int is_nullable; struct vts_table *vts_table; struct fts_table *fts_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
52 v
.add_decl
("struct fts_table \{ struct type *fts[1]; \}; /* fts list of a C type representation. */")
53 v
.add_decl
("struct vts_table \{ struct type *vts[1]; \}; /* vts list of a C type representation. */")
54 # Instance abstract representation
55 v
.add_decl
("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
57 # Declare global instances
58 v
.add_decl
("extern int glob_argc;")
59 v
.add_decl
("extern char **glob_argv;")
60 v
.add_decl
("extern val *glob_sys;")
62 # The main function of the C
63 compiler
.compile_main_function
65 # compile class structures
66 for m
in mainmodule
.in_importation
.greaters
do
67 for mclass
in m
.intro_mclasses
do
68 compiler
.compile_class_to_c
(mclass
)
73 for m
in mainmodule
.in_importation
.greaters
do
74 compiler
.compile_module_to_c
(m
)
77 # compile live & cast type structures
78 var mtypes
= compiler
.do_global_type_coloring
80 compiler
.compile_type_to_c
(t
)
83 # compile live generic types selection structures
84 for mclass
in model
.mclasses
do
85 compiler
.compile_live_gentype_to_c
(mclass
)
88 # for the class_name and output_class_name methods
89 compiler
.compile_class_names
91 write_and_make
(compiler
)
95 # Singleton that store the knowledge about the separate compilation process
96 class SeparateCompiler
97 super GlobalCompiler # TODO better separation of concerns
99 private var undead_types
: Set[MType] = new HashSet[MType]
100 protected var typeids
: HashMap[MType, Int] protected writable = new HashMap[MType, Int]
102 private var type_colors
: Map[MType, Int] = typeids
103 private var type_tables
: nullable Map[MType, Array[nullable MType]] = null
105 private var livetypes_colors
: nullable Map[MType, Int]
106 private var livetypes_tables
: nullable Map[MClass, Array[nullable Object]]
107 private var livetypes_tables_sizes
: nullable Map[MClass, Array[Int]]
109 protected var class_colors
: Map[MClass, Int] protected writable
111 protected var method_colors
: Map[MMethod, Int] protected writable
112 protected var method_tables
: Map[MClass, Array[nullable MMethodDef]] protected writable
114 protected var attr_colors
: Map[MAttribute, Int] protected writable
115 protected var attr_tables
: Map[MClass, Array[nullable MAttributeDef]] protected writable
117 private var vt_colors
: Map[MVirtualTypeProp, Int]
118 private var vt_tables
: Map[MClass, Array[nullable MVirtualTypeDef]]
120 private var ft_colors
: Map[MParameterType, Int]
121 private var ft_tables
: Map[MClass, Array[nullable MParameterType]]
123 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
125 var class_coloring
= new ClassColoring(mainmodule
)
126 self.class_colors
= class_coloring
.colorize
(mmbuilder
.model
.mclasses
)
129 var method_coloring
= new MethodColoring(class_coloring
)
130 self.method_colors
= method_coloring
.colorize
131 self.method_tables
= method_coloring
.build_property_tables
133 # attributes coloration
134 var attribute_coloring
= new AttributeColoring(class_coloring
)
135 self.attr_colors
= attribute_coloring
.colorize
136 self.attr_tables
= attribute_coloring
.build_property_tables
139 var vt_coloring
= new VTColoring(class_coloring
)
140 self.vt_colors
= vt_coloring
.colorize
141 self.vt_tables
= vt_coloring
.build_property_tables
144 var ft_coloring
= new FTColoring(class_coloring
)
145 self.ft_colors
= ft_coloring
.colorize
146 self.ft_tables
= ft_coloring
.build_ft_tables
149 protected fun compile_class_names
do
151 # Build type names table
152 var type_array
= new Array[nullable MType]
153 for t
, i
in typeids
do
154 if i
>= type_array
.length
then
160 var v
= self.new_visitor
161 self.header
.add_decl
("extern const char const * class_names[];")
162 v
.add
("const char const * class_names[] = \{")
163 for t
in type_array
do
173 # colorize live types of the program
174 private fun do_global_type_coloring
: Set[MType] do
175 var mtypes
= new HashSet[MType]
176 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
177 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
178 mtypes
.add_all
(self.undead_types
)
180 self.undead_types
.clear
181 for mtype
in mtypes
do
182 # add formal types arguments to mtypes
183 if mtype
isa MGenericType then
184 for ft
in mtype
.arguments
do
185 if ft
.need_anchor
then
186 print
("Why do we need anchor here ?")
189 self.undead_types
.add
(ft
)
192 var mclass_type
: MClassType
193 if mtype
isa MNullableType then
194 mclass_type
= mtype
.mtype
.as(MClassType)
196 mclass_type
= mtype
.as(MClassType)
198 # add virtual types to mtypes
199 for vt
in self.vt_tables
[mclass_type
.mclass
] do
201 var anchored
= vt
.bound
.anchor_to
(self.mainmodule
, mclass_type
)
202 self.undead_types
.add
(anchored
)
206 mtypes
.add_all
(self.undead_types
)
209 for mtype
in mtypes
do
210 self.typeids
[mtype
] = self.typeids
.length
213 # colorize live entries
214 var entries_coloring
= new LiveEntryColoring
215 self.livetypes_colors
= entries_coloring
.colorize
(mtypes
)
216 self.livetypes_tables
= entries_coloring
.build_livetype_tables
(mtypes
)
217 self.livetypes_tables_sizes
= entries_coloring
.livetypes_tables_sizes
220 var type_coloring
= new TypeColoring(self.mainmodule
, mtypes
)
221 self.type_colors
= type_coloring
.colorize
(mtypes
)
222 self.type_tables
= type_coloring
.build_type_tables
(mtypes
, type_colors
)
227 # declare live generic types tables selection
228 private fun compile_live_gentype_to_c
(mclass
: MClass) do
229 if mclass
.arity
> 0 then
230 if self.livetypes_tables
.has_key
(mclass
) then
231 var table
= self.livetypes_tables
[mclass
]
232 var sign
= self.livetypes_tables_sizes
[mclass
]
233 var table_buffer
= new Buffer.from
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}] = \{\n")
234 compile_livetype_table
(table
, table_buffer
, 1, mclass
.arity
)
235 table_buffer
.append
("\};")
237 var v
= new SeparateCompilerVisitor(self)
238 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
239 v
.add_decl
(table_buffer
.to_s
)
241 var sign
= new Array[Int].filled_with
(0, mclass
.arity
)
242 var v
= new SeparateCompilerVisitor(self)
243 self.header
.add_decl
("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
244 v
.add_decl
("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
249 private fun compile_livetype_table
(table
: Array[nullable Object], buffer
: Buffer, depth
: Int, max
: Int) do
253 buffer
.append
("NULL,\n")
255 buffer
.append
("\{\},\n")
257 else if obj
isa MClassType then
258 buffer
.append
("(struct type*) &type_{obj.c_name}, /* {obj} */\n")
259 else if obj
isa Array[nullable Object] then
260 buffer
.append
("\{\n")
261 compile_livetype_table
(obj
, buffer
, depth
+ 1, max
)
262 buffer
.append
("\},\n")
267 # Separately compile all the method definitions of the module
268 fun compile_module_to_c
(mmodule
: MModule)
270 for cd
in mmodule
.mclassdefs
do
271 for pd
in cd
.mpropdefs
do
272 if not pd
isa MMethodDef then continue
273 #print "compile {pd} @ {cd} @ {mmodule}"
274 var r
= new SeparateRuntimeFunction(pd
)
276 if true or cd
.bound_mtype
.ctype
!= "val*" then
277 var r2
= new VirtualRuntimeFunction(pd
)
278 r2
.compile_to_c
(self)
284 # Globaly compile the type structure of a live type
285 fun compile_type_to_c
(mtype
: MType)
287 var c_name
= mtype
.c_name
288 var v
= new SeparateCompilerVisitor(self)
289 v
.add_decl
("/* runtime type {mtype} */")
291 var mclass_type
: MClassType
292 if mtype
isa MNullableType then
293 mclass_type
= mtype
.mtype
.as(MClassType)
295 mclass_type
= mtype
.as(MClassType)
298 # extern const struct type_X
299 self.header
.add_decl
("extern const struct type_{c_name} type_{c_name};")
300 self.header
.add_decl
("struct type_{c_name} \{")
301 self.header
.add_decl
("int id;")
302 self.header
.add_decl
("int color;")
303 self.header
.add_decl
("int livecolor;")
304 self.header
.add_decl
("short int is_nullable;")
305 self.header
.add_decl
("const struct vts_table_{c_name} *vts_table;")
306 self.header
.add_decl
("const struct fts_table_{c_name} *fts_table;")
307 self.header
.add_decl
("int table_size;")
308 self.header
.add_decl
("int type_table[{self.type_tables[mtype].length}];")
309 self.header
.add_decl
("\};")
311 # extern const struct vts_table_X vts_table_X
312 self.header
.add_decl
("extern const struct vts_table_{c_name} vts_table_{c_name};")
313 self.header
.add_decl
("struct vts_table_{c_name} \{")
314 self.header
.add_decl
("struct type *vts[{self.vt_tables[mclass_type.mclass].length}];")
315 self.header
.add_decl
("\};")
317 # extern const struct fst_table_X fst_table_X
318 self.header
.add_decl
("extern const struct fts_table_{c_name} fts_table_{c_name};")
319 self.header
.add_decl
("struct fts_table_{c_name} \{")
320 self.header
.add_decl
("struct type *fts[{self.ft_tables[mclass_type.mclass].length}];")
321 self.header
.add_decl
("\};")
323 # const struct type_X
324 v
.add_decl
("const struct type_{c_name} type_{c_name} = \{")
325 v
.add_decl
("{self.typeids[mtype]},")
326 v
.add_decl
("{self.type_colors[mtype]},")
327 v
.add_decl
("{self.livetypes_colors[mtype]},")
328 if mtype
isa MNullableType then
333 v
.add_decl
("&vts_table_{c_name},")
334 v
.add_decl
("&fts_table_{c_name},")
335 v
.add_decl
("{self.type_tables[mtype].length},")
337 for stype
in self.type_tables
[mtype
] do
338 if stype
== null then
339 v
.add_decl
("-1, /* empty */")
341 v
.add_decl
("{self.typeids[stype]}, /* {stype} */")
347 build_fts_table
(mtype
, v
)
348 build_vts_table
(mtype
, v
)
351 # const struct fst_table_X fst_table_X
352 private fun build_fts_table
(mtype
: MType, v
: SeparateCompilerVisitor) do
353 v
.add_decl
("const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name} = \{")
356 var mclass_type
: MClassType
357 if mtype
isa MNullableType then
358 mclass_type
= mtype
.mtype
.as(MClassType)
360 mclass_type
= mtype
.as(MClassType)
363 for ft
in self.ft_tables
[mclass_type
.mclass
] do
365 v
.add_decl
("NULL, /* empty */")
368 if ft
.mclass
== mclass_type
.mclass
then
369 ntype
= mclass_type
.arguments
[ft
.rank
]
371 ntype
= ft
.anchor_to
(self.mainmodule
, mclass_type
)
373 if self.typeids
.has_key
(ntype
) then
374 v
.add_decl
("(struct type*)&type_{ntype.c_name}, /* {ft} ({ntype}) */")
376 v
.add_decl
("NULL, /* empty ({ft} not a live type) */")
384 # const struct vts_table_X vts_table_X
385 private fun build_vts_table
(mtype
: MType, v
: SeparateCompilerVisitor) do
386 v
.add_decl
("const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name} = \{")
389 var mclass_type
: MClassType
390 if mtype
isa MNullableType then
391 mclass_type
= mtype
.mtype
.as(MClassType)
393 mclass_type
= mtype
.as(MClassType)
396 for vt
in self.vt_tables
[mclass_type
.mclass
] do
398 v
.add_decl
("NULL, /* empty */")
401 if bound
== null then
402 #FIXME how can a bound be null here ?
403 print
"No bound found for virtual type {vt} ?"
407 if ntype
isa MNullableType then ntype
= ntype
.mtype
408 if ntype
isa MVirtualType then
409 bound
= ntype
.anchor_to
(self.mainmodule
, mclass_type
)
410 else if ntype
isa MParameterType then
411 bound
= ntype
.anchor_to
(self.mainmodule
, mclass_type
)
412 else if ntype
isa MGenericType and bound
.need_anchor
then
413 bound
= ntype
.anchor_to
(self.mainmodule
, mclass_type
)
414 else if ntype
isa MClassType then
416 print
"NOT YET IMPLEMENTED: mtype_to_livetype with type: {ntype}"
420 if self.typeids
.has_key
(bound
) then
421 v
.add_decl
("(struct type*)&type_{bound.c_name}, /* {ntype} */")
423 v
.add_decl
("NULL, /* dead type {ntype} */")
432 # Globally compile the table of the class mclass
433 # In a link-time optimisation compiler, tables are globally computed
434 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
435 fun compile_class_to_c
(mclass
: MClass)
437 var mtype
= mclass
.intro
.bound_mtype
438 var c_name
= mclass
.c_name
440 var vft
= self.method_tables
[mclass
]
441 var attrs
= self.attr_tables
[mclass
]
442 var v
= new SeparateCompilerVisitor(self)
444 v
.add_decl
("/* runtime class {c_name} */")
445 var idnum
= classids
.length
446 var idname
= "ID_" + c_name
447 self.classids
[mtype
] = idname
448 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
450 self.header
.add_decl
("struct class_{c_name} \{")
451 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
452 self.header
.add_decl
("\};")
455 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
456 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
458 for i
in [0 .. vft
.length
[ do
459 var mpropdef
= vft
[i
]
460 if mpropdef
== null then
461 v
.add_decl
("NULL, /* empty */")
463 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
464 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
466 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
473 if mtype
.ctype
!= "val*" then
474 #Build instance struct
475 self.header
.add_decl
("struct instance_{c_name} \{")
476 self.header
.add_decl
("const struct type *type;")
477 self.header
.add_decl
("const struct class *class;")
478 self.header
.add_decl
("{mtype.ctype} value;")
479 self.header
.add_decl
("\};")
481 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
483 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
484 v
.add_decl
("/* allocate {mtype} */")
485 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
486 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
487 v
.add
("res->type = (struct type*) &type_{c_name};")
488 v
.add
("res->class = (struct class*) &class_{c_name};")
489 v
.add
("res->value = value;")
490 v
.add
("return (val*)res;")
495 var is_native_array
= mclass
.name
== "NativeArray"
498 if is_native_array
then
499 sig
= "int length, struct type* type"
501 sig
= "struct type* type"
504 #Build instance struct
505 #extern const struct instance_array__NativeArray instance_array__NativeArray;
506 self.header
.add_decl
("struct instance_{c_name} \{")
507 self.header
.add_decl
("const struct type *type;")
508 self.header
.add_decl
("const struct class *class;")
509 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
510 if is_native_array
then
511 # NativeArrays are just a instance header followed by an array of values
512 self.header
.add_decl
("val* values[0];")
514 self.header
.add_decl
("\};")
517 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
518 v
.add_decl
("/* allocate {mtype} */")
519 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
520 var res
= v
.new_named_var
(mtype
, "self")
522 if is_native_array
then
523 var mtype_elt
= mtype
.arguments
.first
524 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
526 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
528 #v.add("{res} = calloc(sizeof(struct instance_{c_name}), 1);")
529 v
.add
("{res}->type = type;")
530 v
.add
("{res}->class = (struct class*) &class_{c_name};")
532 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
534 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
535 for npropdef
in n
.n_propdefs
do
536 if npropdef
isa AAttrPropdef then
537 npropdef
.init_expr
(v
, res
)
541 v
.add
("return {res};")
545 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
548 # The C function associated to a methoddef separately compiled
549 class SeparateRuntimeFunction
550 super AbstractRuntimeFunction
552 redef fun build_c_name
: String
554 return "{mmethoddef.c_name}"
557 redef fun to_s
do return self.mmethoddef
.to_s
559 redef fun compile_to_c
(compiler
)
561 var mmethoddef
= self.mmethoddef
563 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
564 var v
= compiler
.new_visitor
565 var selfvar
= new RuntimeVariable("self", recv
, recv
)
566 var arguments
= new Array[RuntimeVariable]
567 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
570 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
573 var comment
= new Buffer
574 var ret
= msignature
.return_mtype
576 sig
.append
("{ret.ctype} ")
577 else if mmethoddef
.mproperty
.is_new
then
579 sig
.append
("{ret.ctype} ")
583 sig
.append
(self.c_name
)
584 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
585 comment
.append
("(self: {selfvar}")
586 arguments
.add
(selfvar
)
587 for i
in [0..msignature
.arity
[ do
588 var mtype
= msignature
.mparameters
[i
].mtype
589 if i
== msignature
.vararg_rank
then
590 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
592 comment
.append
(", {mtype}")
593 sig
.append
(", {mtype.ctype} p{i}")
594 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
595 arguments
.add
(argvar
)
600 comment
.append
(": {ret}")
602 compiler
.header
.add_decl
("{sig};")
604 v
.add_decl
("/* method {self} for {comment} */")
605 v
.add_decl
("{sig} \{")
607 frame
.returnvar
= v
.new_var
(ret
)
609 frame
.returnlabel
= v
.get_name
("RET_LABEL")
611 if recv
!= arguments
.first
.mtype
then
612 #print "{self} {recv} {arguments.first}"
614 mmethoddef
.compile_inside_to_c
(v
, arguments
)
616 v
.add
("{frame.returnlabel.as(not null)}:;")
618 v
.add
("return {frame.returnvar.as(not null)};")
624 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
625 # The first parameter (the reciever) is always typed by val* in order to accept an object value
626 class VirtualRuntimeFunction
627 super AbstractRuntimeFunction
629 redef fun build_c_name
: String
631 return "VIRTUAL_{mmethoddef.c_name}"
634 redef fun to_s
do return self.mmethoddef
.to_s
636 redef fun compile_to_c
(compiler
)
638 var mmethoddef
= self.mmethoddef
640 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
641 var v
= compiler
.new_visitor
642 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
643 var arguments
= new Array[RuntimeVariable]
644 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
648 var comment
= new Buffer
650 # Because the function is virtual, the signature must match the one of the original class
651 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
652 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
653 var ret
= msignature
.return_mtype
655 sig
.append
("{ret.ctype} ")
656 else if mmethoddef
.mproperty
.is_new
then
658 sig
.append
("{ret.ctype} ")
662 sig
.append
(self.c_name
)
663 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
664 comment
.append
("(self: {selfvar}")
665 arguments
.add
(selfvar
)
666 for i
in [0..msignature
.arity
[ do
667 var mtype
= msignature
.mparameters
[i
].mtype
668 if i
== msignature
.vararg_rank
then
669 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
671 comment
.append
(", {mtype}")
672 sig
.append
(", {mtype.ctype} p{i}")
673 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
674 arguments
.add
(argvar
)
679 comment
.append
(": {ret}")
681 compiler
.header
.add_decl
("{sig};")
683 v
.add_decl
("/* method {self} for {comment} */")
684 v
.add_decl
("{sig} \{")
686 frame
.returnvar
= v
.new_var
(ret
)
688 frame
.returnlabel
= v
.get_name
("RET_LABEL")
690 if recv
!= arguments
.first
.mtype
then
691 #print "{self} {recv} {arguments.first}"
693 mmethoddef
.compile_inside_to_c
(v
, arguments
)
695 v
.add
("{frame.returnlabel.as(not null)}:;")
697 v
.add
("return {frame.returnvar.as(not null)};")
702 redef fun call
(v
, arguments
)
709 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
710 class SeparateCompilerVisitor
711 super GlobalCompilerVisitor # TODO better separation of concerns
713 redef fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
715 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
716 var recv
= args
.first
717 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
718 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
720 for i
in [0..msignature
.arity
[ do
721 var t
= msignature
.mparameters
[i
].mtype
722 if i
== msignature
.vararg_rank
then
725 args
[i
+1] = self.autobox
(args
[i
+1], t
)
729 # Box or unbox a value to another type iff a C type conversion is needed
730 # ENSURE: result.mtype.ctype == mtype.ctype
731 redef fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
733 if value
.mtype
.ctype
== mtype
.ctype
then
735 else if value
.mtype
.ctype
== "val*" then
736 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
737 else if mtype
.ctype
== "val*" then
738 var valtype
= value
.mtype
.as(MClassType)
739 var res
= self.new_var
(mtype
)
740 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
741 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
742 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
745 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
748 # Bad things will appen!
749 var res
= self.new_var
(mtype
)
750 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
751 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
756 redef fun send
(mmethod
, arguments
)
758 if arguments
.first
.mcasttype
.ctype
!= "val*" then
759 return self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
762 var res
: nullable RuntimeVariable
763 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
764 var ret
= msignature
.return_mtype
765 if mmethod
.is_new
then
766 ret
= arguments
.first
.mtype
767 res
= self.new_var
(ret
)
768 else if ret
== null then
771 res
= self.new_var
(ret
)
777 var recv
= arguments
.first
780 self.varargize
(msignature
, arguments
)
781 for i
in [0..msignature
.arity
[ do
782 var a
= arguments
[i
+1]
783 var t
= msignature
.mparameters
[i
].mtype
784 if i
== msignature
.vararg_rank
then
785 t
= arguments
[i
+1].mcasttype
787 s
.append
(", {t.ctype}")
788 a
= self.autobox
(a
, t
)
792 var maybenull
= recv
.mcasttype
isa MNullableType
794 self.add
("if ({recv} == NULL) \{")
795 if mmethod
.name
== "==" then
797 var arg
= arguments
[1]
798 if arg
.mcasttype
isa MNullableType then
799 self.add
("{res} = ({arg} == NULL);")
800 else if arg
.mcasttype
isa MNullType then
801 self.add
("{res} = 1; /* is null */")
803 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
805 else if mmethod
.name
== "!=" then
807 var arg
= arguments
[1]
808 if arg
.mcasttype
isa MNullableType then
809 self.add
("{res} = ({arg} != NULL);")
810 else if arg
.mcasttype
isa MNullType then
811 self.add
("{res} = 0; /* is null */")
813 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
816 self.add_abort
("Reciever is null")
818 self.add
("\} else \{")
821 var color
= self.compiler
.as(SeparateCompiler).method_colors
[mmethod
]
823 if ret
== null then r
= "void" else r
= ret
.ctype
824 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
827 self.add
("{res} = {call};")
839 redef fun call
(mmethoddef
, recvtype
, arguments
)
841 var res
: nullable RuntimeVariable
842 var ret
= mmethoddef
.msignature
.return_mtype
843 if mmethoddef
.mproperty
.is_new
then
844 ret
= arguments
.first
.mtype
845 res
= self.new_var
(ret
)
846 else if ret
== null then
849 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
850 res
= self.new_var
(ret
)
853 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
854 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef then
855 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
856 frame
.returnlabel
= self.get_name
("RET_LABEL")
857 frame
.returnvar
= res
858 var old_frame
= self.frame
860 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
861 mmethoddef
.compile_inside_to_c
(self, arguments
)
862 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
864 self.frame
= old_frame
869 self.adapt_signature
(mmethoddef
, arguments
)
872 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
875 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
881 redef fun isset_attribute
(a
, recv
)
883 self.check_recv_notnull
(recv
)
884 var res
= self.new_var
(bool_type
)
885 self.add
("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}] != NULL; /* {a} on {recv.inspect}*/")
889 redef fun read_attribute
(a
, recv
)
891 self.check_recv_notnull
(recv
)
893 # What is the declared type of the attribute?
894 var ret
= a
.intro
.static_mtype
.as(not null)
895 var intromclassdef
= a
.intro
.mclassdef
896 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
898 # Get the attribute or a box (ie. always a val*)
899 var cret
= self.object_type
.as_nullable
900 var res
= self.new_var
(cret
)
902 self.add
("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}]; /* {a} on {recv.inspect} */")
904 # Check for Uninitialized attribute
905 if not ret
isa MNullableType then
906 self.add
("if ({res} == NULL) \{")
907 self.add_abort
("Uninitialized attribute {a.name}")
911 # Return the attribute or its unboxed version
912 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
913 return self.autobox
(res
, ret
)
916 redef fun write_attribute
(a
, recv
, value
)
918 self.check_recv_notnull
(recv
)
920 # What is the declared type of the attribute?
921 var mtype
= a
.intro
.static_mtype
.as(not null)
922 var intromclassdef
= a
.intro
.mclassdef
923 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
925 # Adapt the value to the declared type
926 value
= self.autobox
(value
, mtype
)
927 var attr
= "{recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}]"
928 if mtype
.ctype
!= "val*" then
929 assert mtype
isa MClassType
930 # The attribute is primitive, thus we store it in a box
931 # The trick is to create the box the first time then resuse the box
932 self.add
("if ({attr} != NULL) \{")
933 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
934 self.add
("\} else \{")
935 value
= self.autobox
(value
, self.object_type
.as_nullable
)
936 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
939 # The attribute is not primitive, thus store it direclty
940 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
944 # Build livetype structure retrieving
945 #ENSURE: mtype.need_anchor
946 fun retrieve_anchored_livetype
(mtype
: MGenericType, buffer
: Buffer) do
947 assert mtype
.need_anchor
949 var compiler
= self.compiler
.as(SeparateCompiler)
950 for ft
in mtype
.arguments
do
954 if ntype
isa MNullableType then
958 if ntype
isa MParameterType then
959 var ftcolor
= compiler
.ft_colors
[ntype
]
960 buffer
.append
("[self->type->fts_table->fts[{ftcolor}]->livecolor]")
961 else if ntype
isa MVirtualType then
962 var vtcolor
= compiler
.vt_colors
[ntype
.mproperty
.as(MVirtualTypeProp)]
963 buffer
.append
("[self->type->vts_table->vts[{vtcolor}]->livecolor]")
964 else if ntype
isa MGenericType and ntype
.need_anchor
then
965 var bbuff
= new Buffer
966 retrieve_anchored_livetype
(ntype
, bbuff
)
967 buffer
.append
("[livetypes_{ntype.mclass.c_name}{bbuff.to_s}->livecolor]")
968 else if ntype
isa MClassType then
969 compiler
.undead_types
.add
(ft
)
970 buffer
.append
("[type_{ft.c_name}.livecolor]")
972 self.add
("printf(\"NOT YET IMPLEMENTED: init_instance
(%s
, {mtype}).\\n\
", \"{ft}\
"); exit(1);")
977 redef fun init_instance
(mtype
)
979 var compiler
= self.compiler
.as(SeparateCompiler)
980 if mtype
isa MGenericType and mtype
.need_anchor
then
981 var buff
= new Buffer
982 retrieve_anchored_livetype
(mtype
, buff
)
983 mtype
= self.anchor
(mtype
).as(MClassType)
984 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype
)
986 compiler
.undead_types
.add
(mtype
)
987 return self.new_expr
("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype
)
990 redef fun type_test
(value
, mtype
)
992 var compiler
= self.compiler
.as(SeparateCompiler)
994 var recv
= self.frame
.arguments
.first
995 var recv_boxed
= self.autobox
(recv
, self.object_type
)
997 var res
= self.new_var
(bool_type
)
999 var cltype
= self.get_name
("cltype")
1000 self.add_decl
("int {cltype};")
1001 var idtype
= self.get_name
("idtype")
1002 self.add_decl
("int {idtype};")
1004 var is_nullable
= self.get_name
("is_nullable")
1005 self.add_decl
("short int {is_nullable};")
1007 var boxed
= self.autobox
(value
, self.object_type
)
1010 if ntype
isa MNullableType then
1014 if ntype
isa MParameterType then
1015 var ftcolor
= compiler
.ft_colors
[ntype
]
1016 self.add
("{cltype} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->color;")
1017 self.add
("{idtype} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->id;")
1018 self.add
("{is_nullable} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->is_nullable;")
1019 else if ntype
isa MGenericType and ntype
.need_anchor
then
1020 var buff
= new Buffer
1021 retrieve_anchored_livetype
(ntype
, buff
)
1022 self.add
("{cltype} = livetypes_{ntype.mclass.c_name}{buff.to_s}->color;")
1023 self.add
("{idtype} = livetypes_{ntype.mclass.c_name}{buff.to_s}->id;")
1024 self.add
("{is_nullable} = livetypes_{ntype.mclass.c_name}{buff.to_s}->is_nullable;")
1025 else if ntype
isa MClassType then
1026 compiler
.undead_types
.add
(mtype
)
1027 self.add
("{cltype} = type_{mtype.c_name}.color;")
1028 self.add
("{idtype} = type_{mtype.c_name}.id;")
1029 self.add
("{is_nullable} = type_{mtype.c_name}.is_nullable;")
1030 else if ntype
isa MVirtualType then
1031 var vtcolor
= compiler
.vt_colors
[ntype
.mproperty
.as(MVirtualTypeProp)]
1032 self.add
("{cltype} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->color;")
1033 self.add
("{idtype} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->id;")
1034 self.add
("{is_nullable} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->is_nullable;")
1036 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{boxed.inspect}\
"); exit(1);")
1039 if mtype
isa MNullableType then
1040 self.add
("{is_nullable} = 1;")
1043 # check color is in table
1044 self.add
("if({boxed} == NULL) \{")
1045 self.add
("{res} = {is_nullable};")
1046 self.add
("\} else \{")
1047 self.add
("if({cltype} >= {boxed}->type->table_size) \{")
1048 self.add
("{res} = 0;")
1049 self.add
("\} else \{")
1050 self.add
("{res} = {boxed}->type->type_table[{cltype}] == {idtype};")
1057 redef fun is_same_type_test
(value1
, value2
)
1059 var res
= self.new_var
(bool_type
)
1060 # Swap values to be symetric
1061 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1066 if value1
.mtype
.ctype
!= "val*" then
1067 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
1068 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1069 else if value2
.mtype
.ctype
!= "val*" then
1070 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1072 var mtype1
= value1
.mtype
.as(MClassType)
1073 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1076 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1081 redef fun class_name_string
(value
)
1083 var res
= self.get_name
("var_class_name")
1084 self.add_decl
("const char *{res};")
1085 self.add
("{res} = class_names[{value}->type->id];")
1089 redef fun equal_test
(value1
, value2
)
1091 var res
= self.new_var
(bool_type
)
1092 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1097 if value1
.mtype
.ctype
!= "val*" then
1098 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
1099 self.add
("{res} = {value1} == {value2};")
1100 else if value2
.mtype
.ctype
!= "val*" then
1101 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1103 var mtype1
= value1
.mtype
.as(MClassType)
1104 self.add
("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1105 self.add
("if ({res}) \{")
1106 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1110 var s
= new Array[String]
1111 # This is just ugly on so many level. this works but must be rewriten
1112 for t
in self.compiler
.live_primitive_types
do
1113 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1114 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1115 s
.add
"({value1}->class == (struct class*)&class_{t.c_name} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1118 self.add
("{res} = {value1} == {value2};")
1120 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class && ({s.join(" || ")}));")
1126 redef fun array_instance
(array
, elttype
)
1128 var compiler
= self.compiler
.as(SeparateCompiler)
1129 var nclass
= self.get_class
("NativeArray")
1130 elttype
= self.anchor
(elttype
)
1131 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
1132 var res
= self.init_instance
(arraytype
)
1133 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1134 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1136 compiler
.undead_types
.add
(nat
.mtype
.as(MClassType))
1137 self.add
("{nat} = NEW_{nclass.c_name}({array.length}, (struct type *) &type_{nat.mtype.c_name});")
1138 for i
in [0..array
.length
[ do
1139 var r
= self.autobox
(array
[i
], self.object_type
)
1140 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1142 var length
= self.int_instance
(array
.length
)
1143 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1144 self.check_init_instance
(res
)
1149 redef fun native_array_def
(pname
, ret_type
, arguments
)
1151 var elttype
= arguments
.first
.mtype
1152 var nclass
= self.get_class
("NativeArray")
1153 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1154 if pname
== "[]" then
1155 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1157 else if pname
== "[]=" then
1158 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1160 else if pname
== "copy_to" then
1161 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1162 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1167 redef fun calloc_array
(ret_type
, arguments
)
1169 var ret
= ret_type
.as(MGenericType)
1170 var compiler
= self.compiler
.as(SeparateCompiler)
1171 compiler
.undead_types
.add
(ret
)
1172 var mclass
= self.get_class
("ArrayCapable")
1173 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1174 var color
= compiler
.ft_colors
[ft
]
1175 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]}, (struct type*) livetypes_array__NativeArray[self->type->fts_table->fts[{color}]->livecolor])", ret_type
))
1180 # Return the name of the C structure associated to a Nit class
1181 fun c_name
: String do
1182 var res
= self.c_name_cache
1183 if res
!= null then return res
1184 res
= "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1185 self.c_name_cache
= res
1188 private var c_name_cache
: nullable String