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.
17 # Global compilation of a Nit program
19 # Techniques used are:
20 # * heterogeneous generics
24 module global_compiler
28 import auto_super_init
29 import rapid_type_analysis
31 redef class ToolContext
33 var opt_output
: OptionString = new OptionString("Output file", "-o", "--output")
36 var opt_no_cc
: OptionBool = new OptionBool("Do not invoke C compiler", "--no-cc")
39 var opt_hardening
: OptionBool = new OptionBool("Generate contracts in the C code against bugs in the compiler", "--hardening")
44 self.option_context
.add_option
(self.opt_output
, self.opt_no_cc
, self.opt_hardening
)
48 redef class ModelBuilder
49 # Entry point to performs a global compilation on the AST of a complete program.
50 # `mainmodule` is the main module of the program
51 # `runtime_type_analysis` is a already computer type analysis.
52 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
55 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
57 var compiler
= new GlobalCompiler(mainmodule
, runtime_type_analysis
, self)
58 var v
= new GlobalCompilerVisitor(compiler
)
60 v
.add_decl
("#include <stdlib.h>")
61 v
.add_decl
("#include <stdio.h>")
62 v
.add_decl
("#include <string.h>")
64 # TODO: Better way to activate the GC
65 v
.add_decl
("#include <gc/gc.h>")
66 #v.add_decl("#define GC_MALLOC(x) calloc(1, (x))")
68 # Declaration of structures the live Nit types
69 # Each live type is generated as an independent C `struct' type.
70 # They only share a common first field `classid` used to implement the polymorphism.
71 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val' that contains only the `classid` field.
73 v
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
74 for t
in runtime_type_analysis
.live_types
do
75 compiler
.declare_runtimeclass
(v
, t
)
78 # Global variable used by the legacy native interface
80 v
.add_decl
("extern int glob_argc;")
81 v
.add_decl
("extern char **glob_argv;")
82 v
.add_decl
("extern val *glob_sys;")
84 # Class names (for the class_name and output_class_name methods)
86 v
.add_decl
("extern const char const * class_names[];")
87 v
.add
("const char const * class_names[] = \{")
88 for t
in runtime_type_analysis
.live_types
do
89 v
.add
("\"{t}\
", /* {compiler.classid(t)} */")
94 # Init instance code (allocate and init-arguments)
96 for t
in runtime_type_analysis
.live_types
do
97 if t
.ctype
!= "val*" then continue # skip primitive types
98 compiler
.generate_init_instance
(t
)
101 # The main function of the C
103 v
= new GlobalCompilerVisitor(compiler
)
104 v
.add_decl
("int glob_argc;")
105 v
.add_decl
("char **glob_argv;")
106 v
.add_decl
("val *glob_sys;")
107 v
.add_decl
("int main(int argc, char** argv) \{")
108 v
.add
("glob_argc = argc; glob_argv = argv;")
109 var main_type
= mainmodule
.sys_type
110 if main_type
== null then return # Nothing to compile
111 var glob_sys
= v
.init_instance
(main_type
)
112 v
.add
("glob_sys = {glob_sys};")
113 var main_init
= mainmodule
.try_get_primitive_method
("init", main_type
)
114 if main_init
!= null then
115 v
.send
(main_init
, [glob_sys
])
117 var main_method
= mainmodule
.try_get_primitive_method
("main", main_type
)
118 if main_method
!= null then
119 v
.send
(main_method
, [glob_sys
])
123 # Compile until all runtime_functions are visited
125 while not compiler
.todos
.is_empty
do
126 var m
= compiler
.todos
.shift
127 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
128 m
.compile_to_c
(compiler
)
130 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
132 # Generate the .h and .c files
133 # A single C file regroups many compiled rumtime functions
134 # 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
136 var outname
= self.toolcontext
.opt_output
.value
137 if outname
== null then
138 outname
= "{mainmodule.name}.bin"
141 var hfilename
= ".nit_compile/{mainmodule.name}.1.h"
142 var h
= new OFStream.open
(hfilename
)
143 for l
in compiler
.header
.decl_lines
do
149 var cfiles
= new Array[String]
151 var file
: nullable OFStream = null
156 for vis
in compiler
.visitors
do
157 count
+= vis
.lines
.length
158 if file
== null or count
> 10000 then
160 if file
!= null then file
.close
161 var cfilename
= ".nit_compile/{mainmodule.name}.{i}.c"
162 cfiles
.add
(cfilename
)
163 file
= new OFStream.open
(cfilename
)
164 file
.write
"#include \"{mainmodule.name}.1.h\
"\n"
165 count
= vis
.lines
.length
167 if vis
!= compiler
.header
then
168 for l
in vis
.decl_lines
do
173 for l
in vis
.lines
do
178 if file
!= null then file
.close
180 self.toolcontext
.info
("Total C source files to compile: {cfiles.length}", 2)
182 # Generate the Makefile
184 var makename
= ".nit_compile/{mainmodule.name}.mk"
185 var makefile
= new OFStream.open
(makename
)
187 makefile
.write
("CC = ccache cc\nCFLAGS = -g -O2\nLDFLAGS ?= \nLDLIBS ?= -lm -lgc\n\n")
188 makefile
.write
("all: {outname}\n\n")
190 var ofiles
= new Array[String]
191 # Compile each generated file
193 var o
= f
.strip_extension
(".c") + ".o"
194 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
197 # Compile each required extern body into a specific .o
198 for f
in compiler
.extern_bodies
do
200 var o
= ".nit_compile/{mainmodule.name}.{i}.o"
201 makefile
.write
("{o}: {f}\n\t$(CC) $(CFLAGS) -D NONITCNI -c -o {o} {f}\n\n")
205 makefile
.write
("{outname}: {ofiles.join(" ")}\n\t$(CC) $(LDFLAGS) $(LDLIBS) -o {outname} {ofiles.join(" ")}\n\n")
207 makefile
.write
("clean:\n\trm {ofiles.join(" ")} 2>/dev/null\n\n")
209 self.toolcontext
.info
("Generated makefile: {makename}", 2)
212 self.toolcontext
.info
("*** END COMPILING TO C: {time1-time0} ***", 2)
214 # Execute the Makefile
216 if self.toolcontext
.opt_no_cc
.value
then return
219 self.toolcontext
.info
("*** COMPILING C ***", 1)
220 self.toolcontext
.info
("make -B -f {makename} -j 4", 2)
223 if self.toolcontext
.verbose_level
>= 3 then
224 res
= sys
.system
("make -B -f {makename} -j 4 2>&1")
226 res
= sys
.system
("make -B -f {makename} -j 4 2>&1 >/dev/null")
229 toolcontext
.error
(null, "make failed! Error code: {res}.")
233 self.toolcontext
.info
("*** END COMPILING C: {time1-time0} ***", 2)
237 # Singleton that store the knowledge about the compilation process
238 private class GlobalCompiler
239 # The main module of the program
240 var mainmodule
: MModule
242 # The result of the RTA (used to know live types and methods)
243 var runtime_type_analysis
: RapidTypeAnalysis
245 # The modeulbuilder used to know the model and the AST
246 var modelbuilder
: ModelBuilder
248 # Is hardening asked? (see --hardening)
249 fun hardening
: Bool do return self.modelbuilder
.toolcontext
.opt_hardening
.value
251 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, modelbuilder
: ModelBuilder)
253 self.mainmodule
= mainmodule
254 self.runtime_type_analysis
= runtime_type_analysis
255 self.modelbuilder
= modelbuilder
256 self.live_primitive_types
= new Array[MClassType]
257 for t
in runtime_type_analysis
.live_types
do
258 if t
.ctype
!= "val*" then
259 self.live_primitive_types
.add
(t
)
264 # Subset of runtime_type_analysis.live_types that contains only primitive types
265 # Used to implement the equal test
266 var live_primitive_types
: Array[MClassType]
268 # runtime_functions that need to be compiled
269 private var todos
: List[RuntimeFunction] = new List[RuntimeFunction]
271 # runtime_functions already seen (todo or done)
272 private var seen
: HashSet[RuntimeFunction] = new HashSet[RuntimeFunction]
273 fun todo
(m
: RuntimeFunction)
275 if seen
.has
(m
) then return
280 # Where global declaration are stored (the main .h)
282 # FIXME: should not be a vistor but just somewhere to store lines
283 # FIXME: should not have a global .h since it does not help recompilations
284 var header
: nullable GlobalCompilerVisitor = null
286 # The list of all associated visitors
287 # Used to generate .c files
288 # FIXME: should not be vistors but just somewhere to store lines
289 private var visitors
: List[GlobalCompilerVisitor] = new List[GlobalCompilerVisitor]
291 # List of additional .c files required to compile (native interface)
292 var extern_bodies
= new ArraySet[String]
294 # Return the C symbol associated to a live type runtime
295 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
296 fun classid
(mtype
: MClassType): String
298 if self.classids
.has_key
(mtype
) then
299 return self.classids
[mtype
]
301 print
"No classid for {mtype}"
305 # Cache for classid (computed by declare_runtimeclass)
306 private var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
308 # Declare C structures and identifiers for a runtime class
309 fun declare_runtimeclass
(v
: GlobalCompilerVisitor, mtype
: MClassType)
311 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
312 v
.add_decl
("/* runtime class {mtype} */")
313 var idnum
= classids
.length
314 var idname
= "ID_" + mtype
.c_name
315 self.classids
[mtype
] = idname
316 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
318 v
.add_decl
("struct {mtype.c_name} \{")
319 v
.add_decl
("int classid; /* must be {idname} */")
321 if mtype
.ctype
!= "val*" then
322 # Is the Nit type is native then the struct is a box with two fields:
323 # * the `classid` to be polymorph
324 # * the `value` that contains the native value.
325 v
.add_decl
("{mtype.ctype} value;")
328 # Collect all attributes and associate them a field in the structure.
329 # Note: we do not try to optimize the order and helps CC to optimize the client code.
330 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
331 for p
in cd
.intro_mproperties
do
332 if not p
isa MAttribute then continue
333 var t
= p
.intro
.static_mtype
.as(not null)
334 t
= t
.anchor_to
(self.mainmodule
, mtype
)
335 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
341 # Generate the init-instance of a live type (allocate + init-instance)
342 fun generate_init_instance
(mtype
: MClassType)
344 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
345 assert mtype
.ctype
== "val*"
346 var v
= new GlobalCompilerVisitor(self)
348 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}(void);")
349 v
.add_decl
("/* allocate {mtype} */")
350 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}(void) \{")
351 var res
= v
.new_var
(mtype
)
353 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
354 v
.add
("{res}->classid = {self.classid(mtype)};")
356 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
)
358 var n
= self.modelbuilder
.mclassdef2nclassdef
[cd
]
359 for npropdef
in n
.n_propdefs
do
360 if npropdef
isa AAttrPropdef then
361 npropdef
.init_expr
(v
, res
)
365 v
.add
("return {res};")
369 # look for a needed .h and .c file for a given .nit source-file
370 # FIXME: bad API, parameter should be a MModule, not its source-file
371 fun add_extern
(file
: String)
373 file
= file
.strip_extension
(".nit")
374 var tryfile
= file
+ ".nit.h"
375 if tryfile
.file_exists
then
376 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
378 tryfile
= file
+ "_nit.h"
379 if tryfile
.file_exists
then
380 self.header
.add_decl
("#include \"{"..".join_path(tryfile)}\
"")
382 tryfile
= file
+ ".nit.c"
383 if tryfile
.file_exists
then
384 self.extern_bodies
.add
(tryfile
)
386 tryfile
= file
+ "_nit.c"
387 if tryfile
.file_exists
then
388 self.extern_bodies
.add
(tryfile
)
392 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
396 # Mangle a string to be a unique valid C identifier
397 fun to_cmangle
: String
400 var underscore
= false
402 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
408 res
.append
('_'.ascii
.to_s
)
411 if c
>= '0' and c
<= '9' then
414 else if c
== '_' then
419 res
.append
(c
.ascii
.to_s
)
427 # Escape " \ ' and non printable characters for literal C strings or characters
428 fun escape_to_c
: String
434 else if c
== '\0' then
436 else if c
== '"' then
438 else if c == '\'' then
440 else if c == '\\
' then
442 else if c.ascii < 32 then
443 b.append("\\{c.ascii.to_base(8, false)}")
453 # Return the C type associated to a given Nit static type
459 # Return the name of the C structure associated to a Nit live type
460 # FIXME: move to GlobalCompiler so we can check that self is a live type
461 fun c_name: String is abstract
462 private var c_name_cache: nullable String
465 redef class MClassType
468 var res = self.c_name_cache
469 if res != null then return res
470 res = "{mclass.intro_mmodule.name.to_cmangle}__{mclass.name.to_cmangle}"
471 self.c_name_cache = res
475 redef fun ctype: String
477 if mclass.name == "Int" then
479 else if mclass.name == "Bool" then
481 else if mclass.name == "Char" then
483 else if mclass.name == "Float" then
485 else if mclass.name == "NativeString" then
487 else if mclass.name == "NativeArray" then
488 assert self isa MGenericType
489 return "{self.arguments.first.ctype}*"
490 else if mclass.kind == extern_kind then
498 redef class MGenericType
501 var res = self.c_name_cache
502 if res != null then return res
504 for t in self.arguments do
507 self.c_name_cache = res
512 redef class MNullableType
515 var res = self.c_name_cache
516 if res != null then return res
517 res = "nullable_{self.mtype.c_name}"
518 self.c_name_cache = res
523 # A C function associated to a Nit method
524 # Because of customization, a given Nit method can be compiler more that once
525 private abstract class RuntimeFunction
526 # The associated Nit method
527 var mmethoddef: MMethodDef
529 # The mangled c name of the runtime_function
530 fun c_name: String is abstract
532 # Implements a call of the runtime_function
533 # May inline the body or generate a C function call
534 fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable is abstract
536 # Generate the code for the RuntimeFunction
537 # Warning: compile more than once compilation makes CC unhappy
538 fun compile_to_c(compiler: GlobalCompiler) is abstract
541 # A runtime function customized on a specific monomrph receiver type
542 private class CustomizedRuntimeFunction
543 super RuntimeFunction
545 # The considered reciever
546 # (usually is a live type but no strong guarantee)
549 init(mmethoddef: MMethodDef, recv: MClassType)
555 # The mangled c name of the runtime_function
556 redef fun c_name: String
558 var res = self.c_name_cache
559 if res != null then return res
560 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
561 res = self.mmethoddef.c_name
563 res = "{mmethoddef.c_name}__{recv.c_name}"
565 self.c_name_cache = res
569 private var c_name_cache: nullable String = null
572 # used in the compiler worklist
574 if not o isa CustomizedRuntimeFunction then return false
575 if self.mmethoddef != o.mmethoddef then return false
576 if self.recv != o.recv then return false
581 # used in the compiler work-list
583 var res = self.mmethoddef.hash + self.recv.hash
589 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
590 return self.mmethoddef.to_s
592 return "{self.mmethoddef}@{self.recv}"
596 redef fun compile_to_c(compiler)
598 self.mmethoddef.compile_to_c(compiler, self.recv)
601 redef fun call(v: GlobalCompilerVisitor, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
603 var ret = self.mmethoddef.msignature.return_mtype
604 if self.mmethoddef.mproperty.is_new then
605 ret = arguments.first.mtype
608 ret = v.resolve_for(ret, arguments.first)
610 if self.mmethoddef.can_inline(v) then
611 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
612 frame.returnlabel = v.get_name("RET_LABEL")
614 frame.returnvar = v.new_var(ret)
616 var old_frame = v.frame
618 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
619 self.mmethoddef.compile_inside_to_c(v, arguments)
620 v.add("{frame.returnlabel.as(not null)}:(void)0;")
623 return frame.returnvar
625 v.adapt_signature(self.mmethoddef, arguments)
626 v.compiler.todo(self)
628 v.add("{self.c_name}({arguments.join(",")});")
631 var res = v.new_var(ret)
632 v.add("{res} = {self.c_name}({arguments.join(",")});")
638 # A runtime variable hold a runtime value in C.
639 # Runtime variables are associated to Nit local variables and intermediate results in Nit expressions.
641 # 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.
642 private class RuntimeVariable
643 # The name of the variable in the C code
646 # The static type of the variable (as declard in C)
649 # The current casted type of the variable (as known in Nit)
652 # If the variable exaclty a mcasttype?
653 # false (usual value) means that the variable is a mcasttype or a subtype.
654 var is_exact: Bool = false
656 redef fun to_s do return name
661 if self.is_exact then
667 if self.mtype == self.mcasttype then
668 type_str = "{mtype}{exact_str}"
670 type_str = "{mtype}({mcasttype}{exact_str})"
672 return "<{name}:{type_str}>"
676 # A visitor on the AST of property definition that generate the C code.
677 # Because of inlining, a visitor can visit more than one property.
678 private class GlobalCompilerVisitor
679 # The associated compiler
680 var compiler: GlobalCompiler
682 init(compiler: GlobalCompiler)
684 self.compiler = compiler
685 compiler.visitors.add(self)
688 # Alias for self.compiler.mainmodule.object_type
689 fun object_type: MClassType do return self.compiler.mainmodule.object_type
691 # Alias for self.compiler.mainmodule.bool_type
692 fun bool_type: MClassType do return self.compiler.mainmodule.bool_type
694 # Force to get the primitive class named `name' or abort
695 fun get_class
(name
: String): MClass
697 return self.compiler
.mainmodule
.get_primitive_class
(name
)
700 # Force to get the primitive property named `name' in the instance `recv' or abort
701 fun get_property
(name
: String, recv
: MType): MMethod
703 return self.compiler
.mainmodule
.force_get_primitive_method
(name
, recv
)
707 var frame
: nullable Frame
709 # Anchor a type to the main module and the current receiver
710 fun anchor
(mtype
: MType): MType
712 if not mtype
.need_anchor
then return mtype
713 #debug("anchor {mtype} to {self.reciever.as(not null)}:{self.reciever.mtype}")
714 return mtype
.anchor_to
(self.compiler
.mainmodule
, self.frame
.receiver
)
717 # Add a line in the main part of the generated C
724 # (used for local or global declaration)
725 fun add_decl
(s
: String)
727 self.decl_lines
.add
(s
)
730 private var lines
: List[String] = new List[String]
731 private var decl_lines
: List[String] = new List[String]
733 # The current visited AST node
734 var current_node
: nullable AExpr = null
736 # Compile an expression an return its result
737 # `mtype` is the expected return type, pass null if no specific type is expected.
738 fun expr
(nexpr
: AExpr, mtype
: nullable MType): RuntimeVariable
740 var old
= self.current_node
741 self.current_node
= nexpr
742 var res
= nexpr
.expr
(self).as(not null)
743 if mtype
!= null then
744 mtype
= self.anchor
(mtype
)
745 res
= self.autobox
(res
, mtype
)
747 self.current_node
= old
751 # Unsafely cast a value to a new type
752 # ie the result share the same C variable but my have a different mcasttype
753 # NOTE: if the adaptation is useless then `value' is returned as it.
754 # ENSURE: return.name == value.name
755 fun autoadapt
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
757 mtype
= self.anchor
(mtype
)
758 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
762 var valmtype
= value
.mtype
763 if valmtype
isa MNullableType and valmtype
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
764 var res
= new RuntimeVariable(value
.name
, value
.mtype
, valmtype
.mtype
)
767 var res
= new RuntimeVariable(value
.name
, value
.mtype
, mtype
)
772 # Box or unbox a value to another type iff a C type conversion is needed
773 # ENSURE: result.mtype.ctype == mtype.ctype
774 fun autobox
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
776 if value
.mtype
.ctype
== mtype
.ctype
then
778 else if value
.mtype
.ctype
== "val*" then
779 return self.new_expr
("((struct {mtype.c_name}*){value})->value /* autounbox from {value.mtype} to {mtype} */", mtype
)
780 else if mtype
.ctype
== "val*" then
781 var valtype
= value
.mtype
.as(MClassType)
782 var res
= self.new_var
(mtype
)
783 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
784 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
785 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
788 self.add
("{res} = GC_MALLOC(sizeof(struct {valtype.c_name})); /* autobox from {value.mtype} to {mtype} */")
789 self.add
("{res}->classid = {self.compiler.classid(valtype)};")
790 self.add
("((struct {valtype.c_name}*){res})->value = {value};")
793 # Bad things will appen!
794 var res
= self.new_var
(mtype
)
795 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
796 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
801 # Correctly assign a left and a right value
802 # Boxing and unboxing is performed if required
803 fun assign
(left
, right
: RuntimeVariable)
805 right
= self.autobox
(right
, left
.mtype
)
806 self.add
("{left} = {right};")
810 # Alias for `self.expr(nexpr, self.bool_type)'
811 fun expr_bool
(nexpr
: AExpr): RuntimeVariable
813 return expr
(nexpr
, bool_type
)
816 # Compile a statement (if any)
817 fun stmt
(nexpr
: nullable AExpr)
819 if nexpr
== null then return
820 var old
= self.current_node
821 self.current_node
= nexpr
823 self.current_node
= old
826 # Safely show a debug message on the current node and repeat the message in the C code as a comment
827 fun debug
(message
: String)
829 var node
= self.current_node
835 self.add
("/* DEBUG: {message} */")
838 # Return a new uninitialized local runtime_variable
839 fun new_var
(mtype
: MType): RuntimeVariable
841 if mtype
isa MNullType then
842 mtype
= self.object_type
844 mtype
= self.anchor
(mtype
)
846 var name
= self.get_name
("var")
847 var res
= new RuntimeVariable(name
, mtype
, mtype
)
848 self.add_decl
("{mtype.ctype} {name} /* : {mtype} */;")
852 # Return a new local runtime_variable initialized with the C expression `cexpr'.
853 fun new_expr
(cexpr
: String, mtype
: MType): RuntimeVariable
855 var res
= new_var
(mtype
)
856 self.add
("{res} = {cexpr};")
860 # Return the local runtime_variable associated to a Nit local variable
861 fun variable
(variable
: Variable): RuntimeVariable
863 if self.variables
.has_key
(variable
) then
864 return self.variables
[variable
]
866 var name
= self.get_name
("var_{variable.name}")
867 var mtype
= variable
.declared_type
.as(not null)
868 mtype
= self.anchor
(mtype
)
869 var res
= new RuntimeVariable(name
, mtype
, mtype
)
870 self.add_decl
("{mtype.ctype} {name} /* var {variable}: {mtype} */;")
871 self.variables
[variable
] = res
876 private var variables
: HashMap[Variable, RuntimeVariable] = new HashMap[Variable, RuntimeVariable]
878 # Return an unique and stable identifier associated with an escapemark
879 fun escapemark_name
(e
: nullable EscapeMark): String
882 if escapemark_names
.has_key
(e
) then return escapemark_names
[e
]
884 if name
== null then name
= "label"
885 name
= get_name
(name
)
886 escapemark_names
[e
] = name
890 private var escapemark_names
= new HashMap[EscapeMark, String]
892 # Return a new name based on `s' and unique in the visitor
893 fun get_name
(s
: String): String
895 if not self.names
.has
(s
) then
899 var i
= self.last
+ 1
902 if not self.names
.has
(s2
) then
911 private var last
: Int = 0
913 private var names
: HashSet[String] = new HashSet[String]
915 # Generate a return with the value `s'
916 fun ret
(s
: RuntimeVariable)
918 self.assign
(self.frame
.returnvar
.as(not null), s
)
919 self.add
("goto {self.frame.returnlabel.as(not null)};")
922 # The runtime types that are acceptable for a given receiver.
923 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
925 var mtype
= recv
.mcasttype
926 if recv
.is_exact
then
927 assert mtype
isa MClassType
928 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
932 var cache
= self.compiler
.collect_types_cache
933 if cache
.has_key
(mtype
) then
936 var types
= new Array[MClassType]
937 var mainmodule
= self.compiler
.mainmodule
938 for t
in self.compiler
.runtime_type_analysis
.live_types
do
939 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
946 fun resolve_for
(mtype
: MType, recv
: RuntimeVariable): MType
948 if not mtype
.need_anchor
then return mtype
949 #debug("resolve for {mtype} to {recv}:{recv.mcasttype}(declared as {recv.mtype}) (in {self.reciever.to_s}:{self.reciever.mtype})")
950 var res
= mtype
.resolve_for
(recv
.mcasttype
, self.frame
.receiver
, self.compiler
.mainmodule
, true)
954 # Generate a polymorphic send for the method `m' and the arguments `args'
955 fun send
(m
: MMethod, args
: Array[RuntimeVariable]): nullable RuntimeVariable
957 var types
= self.collect_types
(args
.first
)
959 var res
: nullable RuntimeVariable
960 var ret
= m
.intro
.msignature
.return_mtype
962 ret
= args
.first
.mtype
963 res
= self.new_var
(ret
)
964 else if ret
== null then
967 ret
= self.resolve_for
(ret
, args
.first
)
968 res
= self.new_var
(ret
)
971 if types
.is_empty
then
972 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
975 self.add
("/* send {m} on {args.first.inspect} */")
976 if args
.first
.mtype
.ctype
!= "val*" then
977 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, args
.first
.mtype
)
978 if propdefs
.length
== 0 then
979 self.add
("/* skip, no method {m} */")
982 assert propdefs
.length
== 1
983 var propdef
= propdefs
.first
984 var res2
= self.call
(propdef
, args
.first
.mtype
.as(MClassType), args
)
985 if res
!= null then self.assign
(res
, res2
.as(not null))
988 if args
.first
.mcasttype
isa MNullableType then
989 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
990 if m
.name
== "==" then
992 if args
[1].mcasttype
.ctype
== "val*" then
993 self.add
("{res} = ({args[1]} == NULL);")
995 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
997 else if m
.name
== "!=" then
999 if args
[1].mcasttype
.ctype
== "val*" then
1000 self.add
("{res} = ({args[1]} != NULL);")
1002 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
1005 self.add_abort
("Reciever is null")
1009 self.add
("switch({args.first}->classid) \{")
1010 var last
= types
.last
1011 var defaultpropdef
: nullable MMethodDef = null
1013 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
1014 if propdefs
.length
== 0 then
1015 self.add
("/* skip {t}, no method {m} */")
1018 var propdef
= propdefs
.first
1019 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
1020 defaultpropdef
= propdef
1023 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
1024 self.add
("default: /* test {t} */")
1026 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
1028 var res2
= self.call
(propdef
, t
, args
)
1029 if res
!= null then self.assign
(res
, res2
.as(not null))
1032 if defaultpropdef
!= null then
1033 self.add
("default: /* default is Object */")
1034 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
1035 if res
!= null then self.assign
(res
, res2
.as(not null))
1036 else if self.compiler
.hardening
then
1037 self.add
("default: /* bug */")
1038 self.bugtype
(args
.first
)
1044 fun check_valid_reciever
(recvtype
: MClassType)
1046 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
1047 print
"{recvtype} is not a live type"
1051 # Generate a static call on a method definition
1052 fun call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1054 check_valid_reciever
(recvtype
)
1055 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
1056 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
1057 recvtype
= m
.mclassdef
.bound_mtype
1059 var recv
= self.autobox
(args
.first
, recvtype
)
1060 recv
= self.autoadapt
(recv
, recvtype
)
1062 var vararg_rank
= m
.msignature
.vararg_rank
1063 if vararg_rank
>= 0 then
1064 assert args
.length
>= m
.msignature
.arity
+ 1 # because of self
1066 args
= new Array[RuntimeVariable]
1068 args
.add
(rawargs
.first
) # recv
1070 for i
in [0..vararg_rank
[ do
1071 args
.add
(rawargs
[i
+1])
1074 var vararg_lastrank
= vararg_rank
+ rawargs
.length-1-m
.msignature
.arity
1075 var vararg
= new Array[RuntimeVariable]
1076 for i
in [vararg_rank
..vararg_lastrank
] do
1077 vararg
.add
(rawargs
[i
+1])
1079 # FIXME: its it to late to determine the vararg type, this should have been done during a previous analysis
1080 var elttype
= m
.msignature
.mparameters
[vararg_rank
].mtype
1081 elttype
= self.resolve_for
(elttype
, recv
)
1082 args
.add
(self.array_instance
(vararg
, elttype
))
1084 for i
in [vararg_lastrank
+1..rawargs
.length-1
[ do
1085 args
.add
(rawargs
[i
+1])
1090 assert args
.length
== m
.msignature
.arity
+ 1 # because of self
1093 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
1094 return rm
.call
(self, args
)
1097 fun adapt_signature
(m
: MMethodDef, args
: Array[RuntimeVariable])
1099 var recv
= args
.first
1100 for i
in [0..m
.msignature
.arity
[ do
1101 var t
= m
.msignature
.mparameters
[i
].mtype
1102 if i
== m
.msignature
.vararg_rank
then
1105 t
= self.resolve_for
(t
, recv
)
1106 args
[i
+1] = self.autobox
(args
[i
+1], t
)
1110 fun bugtype
(recv
: RuntimeVariable)
1112 if recv
.mtype
.ctype
!= "val*" then return
1113 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
1116 # Generate a polymorphic attribute read
1117 fun read_attribute
(a
: MAttribute, recv
: RuntimeVariable): RuntimeVariable
1119 var types
= self.collect_types
(recv
)
1121 var ret
= a
.intro
.static_mtype
.as(not null)
1122 ret
= self.resolve_for
(ret
, recv
)
1123 var res
= self.new_var
(ret
)
1125 if types
.is_empty
then
1126 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1129 self.add
("/* read {a} on {recv.inspect} */")
1130 self.add
("switch({recv}->classid) \{")
1131 var last
= types
.last
1133 if not self.compiler
.hardening
and t
== last
then
1134 self.add
("default: /*{self.compiler.classid(t)}*/")
1136 self.add
("case {self.compiler.classid(t)}:")
1138 var recv2
= self.autoadapt
(recv
, t
)
1139 var ta
= a
.intro
.static_mtype
.as(not null)
1140 ta
= self.resolve_for
(ta
, recv2
)
1141 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
1142 if not ta
isa MNullableType then
1143 if ta
.ctype
== "val*" then
1144 self.add
("if ({res2} == NULL) \{")
1145 self.add_abort
("Uninitialized attribute {a.name}")
1148 self.add
("/*NOTYET isset on primitive attributes*/")
1151 self.assign
(res
, res2
)
1154 if self.compiler
.hardening
then
1155 self.add
("default: /* Bug */")
1163 # Generate a polymorphic attribute write
1164 fun write_attribute
(a
: MAttribute, recv
: RuntimeVariable, value
: RuntimeVariable)
1166 var types
= self.collect_types
(recv
)
1168 if types
.is_empty
then
1169 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
1172 self.add
("/* write {a} on {recv.inspect} */")
1173 self.add
("switch({recv}->classid) \{")
1174 var last
= types
.last
1176 if not self.compiler
.hardening
and t
== last
then
1177 self.add
("default: /*{self.compiler.classid(t)}*/")
1179 self.add
("case {self.compiler.classid(t)}:")
1181 var recv2
= self.autoadapt
(recv
, t
)
1182 var ta
= a
.intro
.static_mtype
.as(not null)
1183 ta
= self.resolve_for
(ta
, recv2
)
1184 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
1187 if self.compiler
.hardening
then
1188 self.add
("default: /* Bug*/")
1194 # Generate a alloc-instance + init-attributes
1195 fun init_instance
(mtype
: MClassType): RuntimeVariable
1197 mtype
= self.anchor
(mtype
).as(MClassType)
1198 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
1199 debug
"problem: {mtype} was detected dead"
1201 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
1206 # Generate a polymorphic subtype test
1207 fun type_test
(value
: RuntimeVariable, mtype
: MType): RuntimeVariable
1209 mtype
= self.anchor
(mtype
)
1210 var types
= self.collect_types
(value
)
1212 var res
= self.new_var
(bool_type
)
1214 self.add
("/* isa {mtype} on {value.inspect} */")
1215 if value
.mcasttype
isa MNullableType then
1216 self.add
("if ({value} == NULL) \{")
1217 if mtype
isa MNullableType then
1218 self.add
("{res} = 1; /* isa {mtype} */")
1220 self.add
("{res} = 0; /* not isa {mtype} */")
1222 self.add
("\} else ")
1224 self.add
("switch({value}->classid) \{")
1226 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
1227 self.add
("case {self.compiler.classid(t)}: /* {t} */")
1230 self.add
("{res} = 1;")
1232 self.add
("default:")
1233 self.add
("{res} = 0;")
1239 # Generate a Nit "is" for two runtime_variables
1240 fun equal_test
(value1
, value2
: RuntimeVariable): RuntimeVariable
1242 var res
= self.new_var
(bool_type
)
1243 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1248 if value1
.mtype
.ctype
!= "val*" then
1249 if value2
.mtype
.ctype
== value1
.mtype
.ctype
then
1250 self.add
("{res} = {value1} == {value2};")
1251 else if value2
.mtype
.ctype
!= "val*" then
1252 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1254 var mtype1
= value1
.mtype
.as(MClassType)
1255 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
1256 self.add
("if ({res}) \{")
1257 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1261 var s
= new Array[String]
1262 for t
in self.compiler
.live_primitive_types
do
1263 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
1264 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
1265 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
1268 self.add
("{res} = {value1} == {value2};")
1270 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
1276 # Generate a check-init-instance
1277 # TODO: is an empty stub currently
1278 fun check_init_instance
(recv
: RuntimeVariable)
1282 # Generate an integer value
1283 fun int_instance
(value
: Int): RuntimeVariable
1285 var res
= self.new_var
(self.get_class
("Int").mclass_type
)
1286 self.add
("{res} = {value};")
1290 # Generate an array value
1291 fun array_instance
(array
: Array[RuntimeVariable], elttype
: MType): RuntimeVariable
1293 elttype
= self.anchor
(elttype
)
1294 var res
= self.init_instance
(self.get_class
("Array").get_mtype
([elttype
]))
1295 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1296 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
1298 self.add
("{nat} = GC_MALLOC({array.length} * sizeof({elttype.ctype}));")
1299 for i
in [0..array
.length
[ do
1300 var r
= self.autobox
(array
[i
], elttype
)
1301 self.add
("{nat}[{i}] = {r};")
1303 var length
= self.int_instance
(array
.length
)
1304 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1305 self.check_init_instance
(res
)
1310 # Generate a string value
1311 fun string_instance
(string
: String): RuntimeVariable
1313 var mtype
= self.get_class
("String").mclass_type
1314 var name
= self.get_name
("varonce")
1315 self.add_decl
("static {mtype.ctype} {name};")
1316 var res
= self.new_var
(mtype
)
1317 self.add
("if ({name}) \{")
1318 self.add
("{res} = {name};")
1319 self.add
("\} else \{")
1320 var nat
= self.new_var
(self.get_class
("NativeString").mclass_type
)
1321 self.add
("{nat} = \"{string.escape_to_c}\
";")
1322 var res2
= self.init_instance
(mtype
)
1323 self.add
("{res} = {res2};")
1324 var length
= self.int_instance
(string
.length
)
1325 self.send
(self.get_property
("with_native", res
.mtype
), [res
, nat
, length
])
1326 self.check_init_instance
(res
)
1327 self.add
("{name} = {res};")
1332 # Generate generic abort
1333 # used by aborts, asserts, casts, etc.
1334 fun add_abort
(message
: String)
1336 if self.current_node
!= null and self.current_node
.location
.file
!= null then
1337 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});")
1339 self.add
("fprintf(stderr, \"Runtime error
: %s\\n\
", \"{message.escape_to_c}\
");")
1341 self.add
("exit(1);")
1345 # A frame correspond to a visited property in a GlobalCompilerVisitor
1347 # The associated visitor
1349 var visitor
: GlobalCompilerVisitor
1351 # The executed property.
1352 # A Method in case of a call, an attribute in case of a default initialization.
1353 var mpropdef
: MPropDef
1355 # The static type of the receiver
1356 var receiver
: MClassType
1358 # Arguments of the method (the first is the receiver)
1359 var arguments
: Array[RuntimeVariable]
1361 # The runtime_variable associated to the return (in a function)
1362 var returnvar
: nullable RuntimeVariable = null
1364 # The label at the end of the property
1365 var returnlabel
: nullable String = null
1368 redef class MPropDef
1369 private var c_name_cache
: nullable String
1371 # The mangled name associated to the property
1374 var res
= self.c_name_cache
1375 if res
!= null then return res
1376 res
= "{self.mclassdef.mmodule.name.to_cmangle}__{self.mclassdef.mclass.name.to_cmangle}__{self.mproperty.name.to_cmangle}"
1377 self.c_name_cache
= res
1382 redef class MMethodDef
1383 # Can the body be inlined?
1384 private fun can_inline
(v
: GlobalCompilerVisitor): Bool
1386 var modelbuilder
= v
.compiler
.modelbuilder
1387 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1388 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1389 return npropdef
.can_inline
1390 else if self.mproperty
.name
== "init" then
1391 # Automatic free init is always inlined since it is empty or contains only attribtes assigments
1398 # Inline the body in another visitor
1399 private fun compile_inside_to_c
(v
: GlobalCompilerVisitor, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1401 var modelbuilder
= v
.compiler
.modelbuilder
1402 if modelbuilder
.mpropdef2npropdef
.has_key
(self) then
1403 var npropdef
= modelbuilder
.mpropdef2npropdef
[self]
1404 npropdef
.compile_to_c
(v
, self, arguments
)
1405 else if self.mproperty
.name
== "init" then
1406 var nclassdef
= modelbuilder
.mclassdef2nclassdef
[self.mclassdef
]
1407 nclassdef
.compile_to_c
(v
, self, arguments
)
1414 # Compile the body in a new visitor
1415 private fun compile_to_c
(compiler
: GlobalCompiler, recv
: MClassType)
1417 if not recv
.is_subtype
(compiler
.mainmodule
, null, self.mclassdef
.bound_mtype
) then
1418 print
("problem: why do we compile {self} for {recv}?")
1422 var v
= new GlobalCompilerVisitor(compiler
)
1423 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1424 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
1425 selfvar
.is_exact
= true
1427 var arguments
= new Array[RuntimeVariable]
1428 var frame
= new Frame(v
, self, recv
, arguments
)
1431 var sig
= new Buffer
1432 var comment
= new Buffer
1433 var ret
= self.msignature
.return_mtype
1435 ret
= v
.resolve_for
(ret
, selfvar
)
1436 sig
.append
("{ret.ctype} ")
1437 else if self.mproperty
.is_new
then
1439 sig
.append
("{ret.ctype} ")
1443 sig
.append
(self.c_name
)
1444 if recv
!= self.mclassdef
.bound_mtype
then
1445 sig
.append
("__{recv.c_name}")
1447 sig
.append
("({recv.ctype} self")
1448 comment
.append
("(self: {recv}")
1449 arguments
.add
(selfvar
)
1450 for i
in [0..self.msignature
.arity
[ do
1451 var mtype
= self.msignature
.mparameters
[i
].mtype
1452 if i
== self.msignature
.vararg_rank
then
1453 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1455 mtype
= v
.resolve_for
(mtype
, selfvar
)
1456 comment
.append
(", {mtype}")
1457 sig
.append
(", {mtype.ctype} p{i}")
1458 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1459 arguments
.add
(argvar
)
1464 comment
.append
(": {ret}")
1466 compiler
.header
.add_decl
("{sig};")
1468 v
.add_decl
("/* method {self} for {comment} */")
1469 v
.add_decl
("{sig} \{")
1470 #v.add("printf(\"method {self} for {comment}\\n\");")
1472 frame
.returnvar
= v
.new_var
(ret
)
1474 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1476 self.compile_inside_to_c
(v
, arguments
)
1478 v
.add
("{frame.returnlabel.as(not null)}:;")
1480 v
.add
("return {frame.returnvar.as(not null)};")
1486 redef class APropdef
1487 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1489 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name} {mpropdef} at
{location.to_s}\\n\
");")
1490 debug
("Not yet implemented")
1493 private fun can_inline
: Bool do return true
1496 redef class AConcreteMethPropdef
1497 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1499 for i
in [0..mpropdef
.msignature
.arity
[ do
1500 var variable
= self.n_signature
.n_params
[i
].variable
.as(not null)
1501 v
.assign
(v
.variable
(variable
), arguments
[i
+1])
1503 # Call the implicit super-init
1504 var auto_super_inits
= self.auto_super_inits
1505 if auto_super_inits
!= null then
1506 var selfarg
= [arguments
.first
]
1507 for auto_super_init
in auto_super_inits
do
1508 if auto_super_init
.intro
.msignature
.arity
== 0 then
1509 v
.send
(auto_super_init
, selfarg
)
1511 v
.send
(auto_super_init
, arguments
)
1516 v
.stmt
(self.n_block
)
1519 redef fun can_inline
1521 if self.auto_super_inits
!= null then return false
1522 var nblock
= self.n_block
1523 if nblock
== null then return true
1524 if (mpropdef
.mproperty
.name
== "==" or mpropdef
.mproperty
.name
== "!=") and mpropdef
.mclassdef
.mclass
.name
== "Object" then return true
1525 if nblock
isa ABlockExpr and nblock
.n_expr
.length
== 0 then return true
1530 redef class AInternMethPropdef
1531 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1533 var pname
= mpropdef
.mproperty
.name
1534 var cname
= mpropdef
.mclassdef
.mclass
.name
1535 var ret
= mpropdef
.msignature
.return_mtype
1537 ret
= v
.resolve_for
(ret
, arguments
.first
)
1539 if pname
!= "==" and pname
!= "!=" then
1540 v
.adapt_signature
(mpropdef
, arguments
)
1542 if cname
== "Int" then
1543 if pname
== "output" then
1544 v
.add
("printf(\"%ld\\n\
", {arguments.first});")
1546 else if pname
== "object_id" then
1547 v
.ret
(arguments
.first
)
1549 else if pname
== "+" then
1550 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1552 else if pname
== "-" then
1553 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1555 else if pname
== "unary -" then
1556 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1558 else if pname
== "succ" then
1559 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1561 else if pname
== "prec" then
1562 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1564 else if pname
== "*" then
1565 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1567 else if pname
== "/" then
1568 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1570 else if pname
== "%" then
1571 v
.ret
(v
.new_expr
("{arguments[0]} % {arguments[1]}", ret
.as(not null)))
1573 else if pname
== "lshift" then
1574 v
.ret
(v
.new_expr
("{arguments[0]} << {arguments[1]}", ret
.as(not null)))
1576 else if pname
== "rshift" then
1577 v
.ret
(v
.new_expr
("{arguments[0]} >> {arguments[1]}", ret
.as(not null)))
1579 else if pname
== "==" then
1580 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1582 else if pname
== "!=" then
1583 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1584 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1586 else if pname
== "<" then
1587 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1589 else if pname
== ">" then
1590 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1592 else if pname
== "<=" then
1593 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1595 else if pname
== ">=" then
1596 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1598 else if pname
== "to_f" then
1599 v
.ret
(v
.new_expr
("(double){arguments[0]}", ret
.as(not null)))
1601 else if pname
== "ascii" then
1602 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1605 else if cname
== "Char" then
1606 if pname
== "output" then
1607 v
.add
("printf(\"%c\
", {arguments.first});")
1609 else if pname
== "object_id" then
1610 v
.ret
(arguments
.first
)
1612 else if pname
== "==" then
1613 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1615 else if pname
== "!=" then
1616 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1617 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1619 else if pname
== "succ" then
1620 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1622 else if pname
== "prec" then
1623 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1625 else if pname
== "<" then
1626 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1628 else if pname
== ">" then
1629 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1631 else if pname
== "<=" then
1632 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1634 else if pname
== ">=" then
1635 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1637 else if pname
== "to_i" then
1638 v
.ret
(v
.new_expr
("{arguments[0]}-'0'", ret
.as(not null)))
1640 else if pname
== "ascii" then
1641 v
.ret
(v
.new_expr
("(unsigned char){arguments[0]}", ret
.as(not null)))
1644 else if cname
== "Bool" then
1645 if pname
== "output" then
1646 v
.add
("printf({arguments.first}?\"true\\n\
":\"false\\n\
");")
1648 else if pname
== "object_id" then
1649 v
.ret
(arguments
.first
)
1651 else if pname
== "==" then
1652 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1654 else if pname
== "!=" then
1655 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1656 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1659 else if cname
== "Float" then
1660 if pname
== "output" then
1661 v
.add
("printf(\"%f\\n\
", {arguments.first});")
1663 else if pname
== "object_id" then
1664 v
.ret
(v
.new_expr
("(double){arguments.first}", ret
.as(not null)))
1666 else if pname
== "+" then
1667 v
.ret
(v
.new_expr
("{arguments[0]} + {arguments[1]}", ret
.as(not null)))
1669 else if pname
== "-" then
1670 v
.ret
(v
.new_expr
("{arguments[0]} - {arguments[1]}", ret
.as(not null)))
1672 else if pname
== "unary -" then
1673 v
.ret
(v
.new_expr
("-{arguments[0]}", ret
.as(not null)))
1675 else if pname
== "succ" then
1676 v
.ret
(v
.new_expr
("{arguments[0]}+1", ret
.as(not null)))
1678 else if pname
== "prec" then
1679 v
.ret
(v
.new_expr
("{arguments[0]}-1", ret
.as(not null)))
1681 else if pname
== "*" then
1682 v
.ret
(v
.new_expr
("{arguments[0]} * {arguments[1]}", ret
.as(not null)))
1684 else if pname
== "/" then
1685 v
.ret
(v
.new_expr
("{arguments[0]} / {arguments[1]}", ret
.as(not null)))
1687 else if pname
== "==" then
1688 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1690 else if pname
== "!=" then
1691 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1692 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1694 else if pname
== "<" then
1695 v
.ret
(v
.new_expr
("{arguments[0]} < {arguments[1]}", ret
.as(not null)))
1697 else if pname
== ">" then
1698 v
.ret
(v
.new_expr
("{arguments[0]} > {arguments[1]}", ret
.as(not null)))
1700 else if pname
== "<=" then
1701 v
.ret
(v
.new_expr
("{arguments[0]} <= {arguments[1]}", ret
.as(not null)))
1703 else if pname
== ">=" then
1704 v
.ret
(v
.new_expr
("{arguments[0]} >= {arguments[1]}", ret
.as(not null)))
1706 else if pname
== "to_i" then
1707 v
.ret
(v
.new_expr
("(long){arguments[0]}", ret
.as(not null)))
1710 else if cname
== "Char" then
1711 if pname
== "output" then
1712 v
.add
("printf(\"%c\
", {arguments.first});")
1714 else if pname
== "object_id" then
1715 v
.ret
(arguments
.first
)
1717 else if pname
== "==" then
1718 v
.ret
(v
.equal_test
(arguments
[0], arguments
[1]))
1720 else if pname
== "!=" then
1721 var res
= v
.equal_test
(arguments
[0], arguments
[1])
1722 v
.ret
(v
.new_expr
("!{res}", ret
.as(not null)))
1724 else if pname
== "ascii" then
1725 v
.ret
(v
.new_expr
("{arguments[0]}", ret
.as(not null)))
1728 else if cname
== "NativeString" then
1729 if pname
== "[]" then
1730 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1732 else if pname
== "[]=" then
1733 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1735 else if pname
== "copy_to" then
1736 v
.add
("memcpy({arguments[1]}+{arguments[4]},{arguments[0]}+{arguments[3]},{arguments[2]});")
1738 else if pname
== "atoi" then
1739 v
.ret
(v
.new_expr
("atoi({arguments[0]});", ret
.as(not null)))
1742 else if cname
== "NativeArray" then
1743 var elttype
= arguments
.first
.mtype
1744 if pname
== "[]" then
1745 v
.ret
(v
.new_expr
("{arguments[0]}[{arguments[1]}]", ret
.as(not null)))
1747 else if pname
== "[]=" then
1748 v
.add
("{arguments[0]}[{arguments[1]}]={arguments[2]};")
1750 else if pname
== "copy_to" then
1751 v
.add
("memcpy({arguments[1]},{arguments[0]},{arguments[2]}*sizeof({elttype.ctype}));")
1755 if pname
== "exit" then
1756 v
.add
("exit({arguments[1]});")
1758 else if pname
== "sys" then
1759 v
.ret
(v
.new_expr
("glob_sys", ret
.as(not null)))
1761 else if pname
== "calloc_string" then
1762 v
.ret
(v
.new_expr
("(char*)GC_MALLOC({arguments[1]})", ret
.as(not null)))
1764 else if pname
== "calloc_array" then
1765 var elttype
= arguments
.first
.mtype
.supertype_to
(v
.compiler
.mainmodule
,arguments
.first
.mtype
.as(MClassType),v
.get_class
("ArrayCapable")).as(MGenericType).arguments
.first
1766 v
.ret
(v
.new_expr
("({elttype.ctype}*)GC_MALLOC({arguments[1]} * sizeof({elttype.ctype}))", ret
.as(not null)))
1768 else if pname
== "object_id" then
1769 v
.ret
(v
.new_expr
("(long){arguments.first}", ret
.as(not null)))
1771 else if pname
== "is_same_type" then
1772 if arguments
[0].mtype
.ctype
== "val*" then
1773 v
.ret
(v
.new_expr
("{arguments[0]}->classid == {arguments[1]}->classid", ret
.as(not null)))
1775 v
.ret
(v
.new_expr
("{v.compiler.classid(arguments[0].mtype.as(MClassType))} == {arguments[1]}->classid", ret
.as(not null)))
1778 else if pname
== "output_class_name" then
1779 if arguments
[0].mtype
.ctype
== "val*" then
1780 v
.add
("printf(\"%s\\n\
", class_names[{arguments.first}->classid]);")
1782 v
.add
("printf(\"%s\\n\
", class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]);")
1785 else if pname
== "native_class_name" then
1786 if arguments
[0].mtype
.ctype
== "val*" then
1787 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{arguments.first}->classid]", ret
.as(not null)))
1789 v
.ret
(v
.new_expr
("(char*)(void*)class_names[{v.compiler.classid(arguments.first.mtype.as(MClassType))}]", ret
.as(not null)))
1793 v
.add
("printf(\"NOT IMPLEMENTED {class_name}:{mpropdef} at
{location.to_s}\\n\
");")
1794 debug
("Not implemented {mpropdef}")
1798 redef class AExternMethPropdef
1799 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1802 var nextern
= self.n_extern
1803 if nextern
== null then
1804 debug
("{mpropdef} need extern name")
1807 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1808 if location
.file
!= null then
1809 var file
= location
.file
.filename
1810 v
.compiler
.add_extern
(file
)
1812 var res
: nullable RuntimeVariable = null
1813 var ret
= mpropdef
.msignature
.return_mtype
1815 ret
= v
.resolve_for
(ret
, arguments
.first
)
1816 res
= v
.new_var
(ret
)
1820 v
.add
("{externname}({arguments.join(", ")});")
1822 v
.add
("{res} = {externname}({arguments.join(", ")});")
1828 redef class AExternInitPropdef
1829 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1832 var nextern
= self.n_extern
1833 if nextern
== null then
1834 debug
("{mpropdef} need extern name")
1837 externname
= nextern
.text
.substring
(1, nextern
.text
.length-2
)
1838 if location
.file
!= null then
1839 var file
= location
.file
.filename
1840 v
.compiler
.add_extern
(file
)
1842 var ret
= arguments
.first
.mtype
1843 var res
= v
.new_var
(ret
)
1847 v
.add
("{res} = {externname}({arguments.join(", ")});")
1852 redef class AAttrPropdef
1853 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1855 if arguments
.length
== 1 then
1856 var res
= v
.read_attribute
(self.mpropdef
.mproperty
, arguments
.first
)
1857 v
.assign
(v
.frame
.returnvar
.as(not null), res
)
1859 v
.write_attribute
(self.mpropdef
.mproperty
, arguments
.first
, arguments
[1])
1863 private fun init_expr
(v
: GlobalCompilerVisitor, recv
: RuntimeVariable)
1865 var nexpr
= self.n_expr
1866 if nexpr
!= null then
1867 var old_frame
= v
.frame
1868 var frame
= new Frame(v
, self.mpropdef
.as(not null), recv
.mtype
.as(MClassType), [recv
])
1870 var value
= v
.expr
(nexpr
, self.mpropdef
.static_mtype
)
1871 v
.write_attribute
(self.mpropdef
.mproperty
, recv
, value
)
1877 redef class AClassdef
1878 private fun compile_to_c
(v
: GlobalCompilerVisitor, mpropdef
: MMethodDef, arguments
: Array[RuntimeVariable])
1880 if mpropdef
== self.mfree_init
then
1881 var super_inits
= self.super_inits
1882 if super_inits
!= null then
1883 assert arguments
.length
== 1
1884 for su
in super_inits
do
1885 v
.send
(su
, arguments
)
1889 var recv
= arguments
.first
1891 # Collect undefined attributes
1892 for npropdef
in self.n_propdefs
do
1893 if npropdef
isa AAttrPropdef and npropdef
.n_expr
== null then
1894 v
.write_attribute
(npropdef
.mpropdef
.mproperty
, recv
, arguments
[i
])
1904 redef class ADeferredMethPropdef
1905 redef fun compile_to_c
(v
, mpropdef
, arguments
)
1907 v
.add
("printf(\"Not implemented
{class_name} {mpropdef} at
{location.to_s}\\n\
");")
1911 redef fun can_inline
do return true
1915 # Try to compile self as an expression
1916 # Do not call this method directly, use `v.expr' instead
1917 private fun expr
(v
: GlobalCompilerVisitor): nullable RuntimeVariable
1919 debug
("Unimplemented expr {class_name}")
1920 v
.add
("printf(\"NOT YET IMPLEMENTED {class_name}:{location.to_s}\\n\
");")
1921 var mtype
= self.mtype
1922 if mtype
== null then
1925 var res
= v
.new_var
(mtype
)
1926 v
.add
("/* {res} = NOT YET {class_name} */")
1931 # Try to compile self as a statement
1932 # Do not call this method directly, use `v.stmt' instead
1933 private fun stmt
(v
: GlobalCompilerVisitor)
1936 if res
!= null then v
.add
("{res};")
1941 redef class ABlockExpr
1944 for e
in self.n_expr
do
1950 redef class AVardeclExpr
1953 var variable
= self.variable
.as(not null)
1954 var ne
= self.n_expr
1956 var i
= v
.expr
(ne
, variable
.declared_type
)
1957 v
.assign
(v
.variable
(variable
), i
)
1962 redef class AVarExpr
1965 var res
= v
.variable
(self.variable
.as(not null))
1966 var mtype
= self.mtype
.as(not null)
1967 return v
.autoadapt
(res
, mtype
)
1971 redef class AVarAssignExpr
1974 var variable
= self.variable
.as(not null)
1975 var i
= v
.expr
(self.n_value
, variable
.declared_type
)
1976 v
.assign
(v
.variable
(variable
), i
)
1980 redef class AVarReassignExpr
1983 var variable
= self.variable
.as(not null)
1984 var vari
= v
.variable
(variable
)
1985 var value
= v
.expr
(self.n_value
, variable
.declared_type
)
1986 var res
= v
.send
(reassign_property
.mproperty
, [vari
, value
])
1988 v
.assign
(v
.variable
(variable
), res
)
1992 redef class ASelfExpr
1995 return v
.frame
.arguments
.first
1999 redef class AContinueExpr
2002 v
.add
("goto CONTINUE_{v.escapemark_name(self.escapemark)};")
2006 redef class ABreakExpr
2009 v
.add
("goto BREAK_{v.escapemark_name(self.escapemark)};")
2013 redef class AReturnExpr
2016 var nexpr
= self.n_expr
2017 if nexpr
!= null then
2018 var returnvar
= v
.frame
.returnvar
.as(not null)
2019 var i
= v
.expr
(nexpr
, returnvar
.mtype
)
2020 v
.assign
(returnvar
, i
)
2022 v
.add
("goto {v.frame.returnlabel.as(not null)};")
2026 redef class AAbortExpr
2029 v
.add_abort
("Aborted")
2036 var cond
= v
.expr_bool
(self.n_expr
)
2037 v
.add
("if ({cond})\{")
2045 redef class AIfexprExpr
2048 var res
= v
.new_var
(self.mtype
.as(not null))
2049 var cond
= v
.expr_bool
(self.n_expr
)
2050 v
.add
("if ({cond})\{")
2051 v
.assign
(res
, v
.expr
(self.n_then
, null))
2053 v
.assign
(res
, v
.expr
(self.n_else
, null))
2062 v
.stmt
(self.n_block
)
2063 var escapemark
= self.escapemark
2064 if escapemark
!= null then
2065 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2070 redef class AWhileExpr
2074 var cond
= v
.expr_bool
(self.n_expr
)
2075 v
.add
("if (!{cond}) break;")
2076 v
.stmt
(self.n_block
)
2077 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2079 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2083 redef class ALoopExpr
2087 v
.stmt
(self.n_block
)
2088 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2090 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2094 redef class AForExpr
2097 var cl
= v
.expr
(self.n_expr
, null)
2098 var it
= v
.send
(v
.get_property
("iterator", cl
.mtype
), [cl
])
2101 var ok
= v
.send
(v
.get_property
("is_ok", it
.mtype
), [it
])
2103 v
.add
("if(!{ok}) break;")
2104 if self.variables
.length
== 1 then
2105 var i
= v
.send
(v
.get_property
("item", it
.mtype
), [it
])
2107 v
.assign
(v
.variable
(variables
.first
), i
)
2108 else if self.variables
.length
== 2 then
2109 var i
= v
.send
(v
.get_property
("key", it
.mtype
), [it
])
2111 v
.assign
(v
.variable
(variables
[0]), i
)
2112 i
= v
.send
(v
.get_property
("item", it
.mtype
), [it
])
2114 v
.assign
(v
.variable
(variables
[1]), i
)
2118 v
.stmt
(self.n_block
)
2119 v
.add
("CONTINUE_{v.escapemark_name(escapemark)}: (void)0;")
2120 v
.send
(v
.get_property
("next", it
.mtype
), [it
])
2122 v
.add
("BREAK_{v.escapemark_name(escapemark)}: (void)0;")
2126 redef class AAssertExpr
2129 var cond
= v
.expr_bool
(self.n_expr
)
2130 v
.add
("if (!{cond}) \{")
2134 v
.add_abort
("Assert '{nid.text}' failed")
2136 v
.add_abort
("Assert failed")
2145 var res
= v
.new_var
(self.mtype
.as(not null))
2146 var i1
= v
.expr_bool
(self.n_expr
)
2147 v
.add
("if ({i1}) \{")
2150 var i2
= v
.expr_bool
(self.n_expr2
)
2151 v
.add
("{res} = {i2};")
2157 redef class AAndExpr
2160 var res
= v
.new_var
(self.mtype
.as(not null))
2161 var i1
= v
.expr_bool
(self.n_expr
)
2162 v
.add
("if (!{i1}) \{")
2165 var i2
= v
.expr_bool
(self.n_expr2
)
2166 v
.add
("{res} = {i2};")
2172 redef class ANotExpr
2175 var cond
= v
.expr_bool
(self.n_expr
)
2176 return v
.new_expr
("!{cond}", self.mtype
.as(not null))
2180 redef class AOrElseExpr
2183 var res
= v
.new_var
(self.mtype
.as(not null))
2184 var i1
= v
.expr
(self.n_expr
, null)
2185 v
.add
("if ({i1}!=NULL) \{")
2188 var i2
= v
.expr
(self.n_expr2
, null)
2198 var value1
= v
.expr
(self.n_expr
, null)
2199 var value2
= v
.expr
(self.n_expr2
, null)
2200 return v
.equal_test
(value1
, value2
)
2204 redef class AIntExpr
2207 return v
.new_expr
("{self.n_number.text}", self.mtype
.as(not null))
2211 redef class AFloatExpr
2214 return v
.new_expr
("{self.n_float.text}", self.mtype
.as(not null))
2218 redef class ACharExpr
2221 return v
.new_expr
("{self.n_char.text}", self.mtype
.as(not null))
2225 redef class AArrayExpr
2228 var mtype
= self.mtype
.as(MGenericType).arguments
.first
2229 var array
= new Array[RuntimeVariable]
2230 for nexpr
in self.n_exprs
.n_exprs
do
2231 var i
= v
.expr
(nexpr
, mtype
)
2234 return v
.array_instance
(array
, mtype
)
2238 redef class AStringFormExpr
2241 return v
.string_instance
(self.value
.as(not null))
2245 redef class ASuperstringExpr
2248 var array
= new Array[RuntimeVariable]
2249 for ne
in self.n_exprs
do
2250 if ne
isa AStringFormExpr and ne
.value
== "" then continue # skip empty sub-strings
2251 var i
= v
.expr
(ne
, null)
2254 var a
= v
.array_instance
(array
, v
.object_type
)
2255 var res
= v
.send
(v
.get_property
("to_s", a
.mtype
), [a
])
2260 redef class ACrangeExpr
2263 var i1
= v
.expr
(self.n_expr
, null)
2264 var i2
= v
.expr
(self.n_expr2
, null)
2265 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2266 var it
= v
.send
(v
.get_property
("init", res
.mtype
), [res
, i1
, i2
])
2267 v
.check_init_instance
(res
)
2272 redef class AOrangeExpr
2275 var i1
= v
.expr
(self.n_expr
, null)
2276 var i2
= v
.expr
(self.n_expr2
, null)
2277 var res
= v
.init_instance
(self.mtype
.as(MClassType))
2278 var it
= v
.send
(v
.get_property
("without_last", res
.mtype
), [res
, i1
, i2
])
2279 v
.check_init_instance
(res
)
2284 redef class ATrueExpr
2287 return v
.new_expr
("1", self.mtype
.as(not null))
2291 redef class AFalseExpr
2294 return v
.new_expr
("0", self.mtype
.as(not null))
2298 redef class ANullExpr
2301 var res
= v
.new_expr
("NULL", self.mtype
.as(not null))
2306 redef class AIsaExpr
2309 var i
= v
.expr
(self.n_expr
, null)
2310 return v
.type_test
(i
, self.cast_type
.as(not null))
2314 redef class AAsCastExpr
2317 var i
= v
.expr
(self.n_expr
, null)
2318 var cond
= v
.type_test
(i
, self.mtype
.as(not null))
2319 v
.add
("if (!{cond}) \{")
2320 v
.add_abort
("Cast failed")
2326 redef class AAsNotnullExpr
2329 var i
= v
.expr
(self.n_expr
, null)
2330 v
.add
("if ({i} == NULL) \{")
2331 v
.add_abort
("Cast failed")
2337 redef class AParExpr
2340 return v
.expr
(self.n_expr
, null)
2344 redef class AOnceExpr
2347 var mtype
= self.mtype
.as(not null)
2348 var name
= v
.get_name
("varonce")
2349 var guard
= v
.get_name
(name
+ "_guard")
2350 v
.add_decl
("static {mtype.ctype} {name};")
2351 v
.add_decl
("static int {guard};")
2352 var res
= v
.new_var
(mtype
)
2353 v
.add
("if ({guard}) \{")
2354 v
.add
("{res} = {name};")
2356 var i
= v
.expr
(self.n_expr
, mtype
)
2357 v
.add
("{res} = {i};")
2358 v
.add
("{name} = {res};")
2359 v
.add
("{guard} = 1;")
2365 redef class ASendExpr
2368 var recv
= v
.expr
(self.n_expr
, null)
2370 for a
in self.raw_arguments
.as(not null) do
2371 args
.add
(v
.expr
(a
, null))
2373 var mproperty
= self.mproperty
.as(not null)
2374 return v
.send
(mproperty
, args
)
2378 redef class ASendReassignFormExpr
2381 var recv
= v
.expr
(self.n_expr
, null)
2383 for a
in self.raw_arguments
.as(not null) do
2384 args
.add
(v
.expr
(a
, null))
2386 var value
= v
.expr
(self.n_value
, null)
2388 var mproperty
= self.mproperty
.as(not null)
2389 var left
= v
.send
(mproperty
, args
)
2392 var res
= v
.send
(reassign_property
.mproperty
, [left
, value
])
2396 v
.send
(self.write_mproperty
.as(not null), args
)
2400 redef class ASuperExpr
2403 var recv
= v
.frame
.arguments
.first
2405 for a
in self.n_args
.n_exprs
do
2406 args
.add
(v
.expr
(a
, null))
2408 if args
.length
== 1 then
2409 args
= v
.frame
.arguments
2412 var mproperty
= self.mproperty
2413 if mproperty
!= null then
2414 if mproperty
.intro
.msignature
.arity
== 0 then
2418 var res
= v
.send
(mproperty
, args
)
2422 # stantard call-next-method
2423 var mpropdef
= v
.frame
.mpropdef
2424 # FIXME: we do not want an ugly static call!
2425 var mpropdefs
= mpropdef
.mproperty
.lookup_super_definitions
(mpropdef
.mclassdef
.mmodule
, mpropdef
.mclassdef
.bound_mtype
)
2426 if mpropdefs
.length
!= 1 then
2427 debug
("MPRODFEFS for super {mpropdef} for {recv}: {mpropdefs.join(", ")}")
2429 mpropdef
= mpropdefs
.first
2430 assert mpropdef
isa MMethodDef
2431 var res
= v
.call
(mpropdef
, recv
.mtype
.as(MClassType), args
)
2436 redef class ANewExpr
2439 var mproperty
= self.mproperty
.as(not null)
2440 var mtype
= self.mtype
.as(MClassType)
2442 var ctype
= mtype
.ctype
2443 if ctype
== "val*" then
2444 recv
= v
.init_instance
(mtype
)
2445 else if ctype
== "void*" then
2446 recv
= v
.new_expr
("NULL/*special!*/", mtype
)
2448 debug
("cannot new {mtype}")
2452 for a
in self.n_args
.n_exprs
do
2453 args
.add
(v
.expr
(a
, null))
2455 var res2
= v
.send
(mproperty
, args
)
2456 if res2
!= null then
2457 #self.debug("got {res2} from {mproperty}. drop {recv}")
2460 v
.check_init_instance
(recv
)
2465 redef class AAttrExpr
2468 var recv
= v
.expr
(self.n_expr
, null)
2469 var mproperty
= self.mproperty
.as(not null)
2470 return v
.read_attribute
(mproperty
, recv
)
2474 redef class AAttrAssignExpr
2477 var recv
= v
.expr
(self.n_expr
, null)
2478 var i
= v
.expr
(self.n_value
, null)
2479 var mproperty
= self.mproperty
.as(not null)
2480 v
.write_attribute
(mproperty
, recv
, i
)
2484 redef class AAttrReassignExpr
2487 var recv
= v
.expr
(self.n_expr
, null)
2488 var value
= v
.expr
(self.n_value
, null)
2489 var mproperty
= self.mproperty
.as(not null)
2490 var attr
= v
.read_attribute
(mproperty
, recv
)
2491 var res
= v
.send
(reassign_property
.mproperty
, [attr
, value
])
2493 v
.write_attribute
(mproperty
, recv
, res
)
2497 redef class AIssetAttrExpr
2500 redef class ADebugTypeExpr