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 # Compiles extern code within a module to a static library, as needed
16 module on_demand_compiler
22 import naive_interpreter
25 redef class ToolContext
28 var opt_compile_dir
= new OptionString("Directory used to generate temporary files", "--compile-dir")
30 init do option_context
.add_option opt_compile_dir
33 redef class AMethPropdef
34 # Does this method definition use the FFI and is it supported by the interpreter?
36 # * Must use the nested foreign code block of the FFI.
37 # * Must not have callbacks.
38 # * Must be implemented in C.
39 # * Must not have a parameter or return typed with a Nit standard class.
40 fun supported_by_dynamic_ffi
: Bool
42 # If the user specfied `is light_ffi`, it must be supported
43 var nats
= get_annotations
("light_ffi")
44 if nats
.not_empty
then return true
46 var n_extern_code_block
= n_extern_code_block
47 if not (n_extern_calls
== null and n_extern_code_block
!= null and
48 n_extern_code_block
.is_c
) then return false
50 for mparam
in mpropdef
.msignature
.mparameters
do
51 if not mparam
.mtype
.is_cprimitive
then
56 var return_mtype
= mpropdef
.msignature
.return_mtype
57 if return_mtype
!= null and not return_mtype
.is_cprimitive
then
65 redef class NaiveInterpreter
66 redef fun start
(mainmodule
)
70 # Delete temporary files
71 var compile_dir
= compile_dir
72 if compile_dir
.file_exists
then compile_dir
.rmdir
75 # Where to store generated C and extracted code
76 private var compile_dir
: String is lazy
do
77 # Prioritize the user supplied directory
78 var opt
= modelbuilder
.toolcontext
.opt_compile_dir
.value
79 if opt
!= null then return opt
80 return "/tmp/niti_ffi_{process_id}"
83 # Identifier for this process, unique between running interpreters
84 private fun process_id
: Int `{ return getpid(); `}
86 # Path of the compiled foreign code library
88 # TODO change the ".so" extension per platform.
89 fun foreign_code_lib_path(mmodule: MModule): String
91 return compile_dir / mmodule.c_name + ".so"
94 # External compiler used to generate the foreign code library
95 private var c_compiler = "cc"
100 # Compile user FFI code and a standardized API into a `.so
` file
102 # Returns `true` on success.
103 fun compile_foreign_lib(v: NaiveInterpreter): Bool
105 var mmodule = mmodule
106 assert mmodule != null
108 var compile_dir = v.compile_dir
109 var foreign_code_lib_path = v.foreign_code_lib_path(mmodule)
111 if not compile_dir.file_exists then compile_dir.mkdir(0o700)
113 # Compile the common FFI part
114 ensure_compile_ffi_wrapper
115 for mclassdef in mmodule.mclassdefs do for mpropdef in mclassdef.mpropdefs do
116 var anode = v.modelbuilder.mpropdef2node(mpropdef)
117 if mpropdef isa MMethodDef and anode isa AMethPropdef and anode.supported_by_dynamic_ffi then
118 anode.compile_ffi_method(mmodule)
121 mmodule.finalize_ffi_wrapper(compile_dir, mmodule)
123 # Compile the standard API and its implementation for the .so file
124 var ccu = compile_foreign_lib_api(compile_dir)
126 var srcs = [for file in ccu.files do new ExternCFile(file, ""): ExternFile]
127 srcs.add_all mmodule.ffi_files
129 # Compiler options specific to this module
130 var ldflags_array = mmodule.ldflags[""]
131 if ldflags_array.has("-lrt") and system("sh -c 'uname -s 2>/dev/null || echo not' | grep Darwin >/dev/null") == 0 then
132 # Remove -lrt on OS X
133 ldflags_array.remove "-lrt"
135 var ldflags = ldflags_array.join(" ")
138 var pkgconfigs = mmodule.pkgconfigs
140 if not pkgconfigs.is_empty then
142 # Check if the pkgconfig packages are available
143 v.modelbuilder.toolcontext.check_pkgconfig_packages pkgconfigs
144 if not v.modelbuilder.toolcontext.check_errors then return false
146 pkg_cflags = "`pkg-config
--cflags
{pkgconfigs.join(" ")}`"
147 ldflags += " `pkg-config
--libs
{pkgconfigs.join(" ")}`"
150 # Compile each source file to an object file (or equivalent)
151 var object_files = new Array[String]
153 f.compile(v, mmodule, object_files, pkg_cflags)
156 # Link everything in a shared library
157 var cmd = "{v.c_compiler} -Wall -shared -o {foreign_code_lib_path} {object_files.join(" ")} {ldflags}"
158 if system(cmd) != 0 then
159 v.fatal "FFI Error: Failed to link native code using `{cmd}`"
166 # Compile the standard API of the `.so
` file
168 # * The shared structure `nit_call_arg
`.
169 # * Standardized implementation functions entrypoints that relay calls
170 # to the FFI implementation functions.
171 private fun compile_foreign_lib_api(compdir: String): CCompilationUnit
173 var mmodule = mmodule
174 assert mmodule != null
176 # ready extern code compiler
177 var ecc = new CCompilationUnit
179 ecc.body_decl.add """
183 #include <inttypes.h>
185 // C structure behind `CallArg` from the interpreter
186 typedef union nit_call_arg {
193 uint16_t value_UInt16;
195 uint32_t value_UInt32;
203 var used_types = collect_mtypes
204 for t in used_types do
205 if not t.is_cprimitive then
206 ecc.header_c_types.add "typedef void* {t.cname};\n"
210 # TODO callbacks & casts
212 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
213 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
214 npropdef.mpropdef.compile_foreign_code_entry ecc
218 ecc.write_as_foreign_lib_api(mmodule, compdir)
223 # Collect all `MType` use in extern methods within this module
224 private fun collect_mtypes: Set[MType]
226 var used_types = new HashSet[MType]
229 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
230 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
231 var fcs = npropdef.foreign_callbacks
232 used_types.add_all fcs.types
240 redef class CCompilationUnit
241 # Write this compilation unit as the API of a foreign code library
242 private fun write_as_foreign_lib_api(mmodule: MModule, compdir: String)
244 # The FFI expects the support header to end with `._nitni
.h
`
245 var base_name = mmodule.c_name + "._nitni"
246 var guard = mmodule.c_name.to_s.to_upper + "_API_H"
247 var header_comment = """
249 Public API to foreign code of the Nit module {{{mmodule.name}}}
254 var h_file = base_name+".h"
255 var stream = new FileWriter.open(compdir/h_file)
256 stream.write header_comment
261 compile_header_core stream
269 var c_file = base_name+".c"
270 stream = new FileWriter.open(compdir/c_file)
271 stream.write header_comment
273 #include "{{{h_file}}}"
275 compile_body_core stream
278 # Only the C files needs compiling
279 files.add compdir / c_file
283 redef class MMethodDef
284 # Name of the entry point to the implementation function in the foreign lib
285 fun foreign_lib_entry_cname: String do return "entry__{cname}"
287 # Compile the standardized entry point as part of the foreign lib API
288 private fun compile_foreign_code_entry(ecc: CCompilationUnit)
290 var msignature = msignature
291 if msignature == null then return
294 var return_mtype = msignature.return_mtype
295 if mproperty.is_init then return_mtype = mclassdef.mclass.mclass_type
298 if return_mtype != null then
299 c_return_type = return_mtype.cname_blind
300 else c_return_type = "void"
302 var is_init = mproperty.is_init
305 var params = new Array[String]
306 if not is_init then params.add mclassdef.mclass.mclass_type.cname_blind
307 for param in msignature.mparameters do params.add param.mtype.cname_blind
309 # Declare the implementation function as extern
310 var impl_cname = mproperty.build_cname(mclassdef.bound_mtype,
311 mclassdef.mmodule, "___impl", long_signature)
312 ecc.body_decl.add "extern {c_return_type} {impl_cname}({params.join(", ")});\n"
314 # Declare the entry function
315 var foreign_lib_entry_cname = "int {foreign_lib_entry_cname}(int argc, nit_call_arg *argv, nit_call_arg *result)"
316 var fc = new CFunction(foreign_lib_entry_cname)
318 # Check argument count on the library side
320 # This may detect inconsistencies between the interpreter and the generated code.
321 var expected_argc = msignature.arity
322 if not is_init then expected_argc += 1
325 if (argc != {{{expected_argc}}}) {
326 printf("Invalid argument count in `{{{mproperty.full_name}}}`, expected %d, got %d.\\n",
327 argc, {{{expected_argc}}});
332 # Unpack and prepare args for the user code
334 var args_for_call = new Array[String]
336 var mtype = mclassdef.mclass.mclass_type
337 var arg_name = "arg___self"
339 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
340 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
341 args_for_call.add arg_name
345 for param in msignature.mparameters do
346 var mtype = param.mtype
347 var arg_name = "arg__"+param.name
349 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
350 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
351 args_for_call.add arg_name
356 # Call implementation function
357 var args_compressed = args_for_call.join(", ")
358 var method_call = "{impl_cname}({args_compressed})"
359 if return_mtype != null then
361 {{{return_mtype.cname_blind}}} return_value;
364 return_value = {{{method_call}}};
365 result->{{{return_mtype.call_arg_field}}} = return_value;
368 fc.exprs.add " {method_call};\n"
371 fc.exprs.add " return 0;\n"
373 ecc.add_exported_function fc
378 # The interpreter FFI use `void
*` to represent intern data types
379 redef fun cname_blind do return "void*"
381 # Field to store this type in the C structure `nit_call_arg
`
382 private fun call_arg_field: String do return "value_Pointer"
385 redef class MClassType
386 redef fun call_arg_field
388 if is_cprimitive and mclass.kind != extern_kind then
389 return "value_{name}"
394 redef class ExternFile
395 # Compile this source file
396 private fun compile(v: NaiveInterpreter, mmodule: MModule,
397 object_files: Array[String], pkg_cflags: String): Bool is abstract
400 redef class ExternCFile
401 redef fun compile(v, mmodule, object_files, pkg_cflags)
403 var compile_dir = v.compile_dir
404 var cflags = mmodule.cflags[""].join(" ") + " " + pkg_cflags
405 var obj = compile_dir / filename.basename(".c") + ".o"
407 var cmd = "{v.c_compiler} -Wall -c -fPIC -I {compile_dir} -g -o {obj} {compile_dir / filename} {cflags}"
408 if sys.system(cmd) != 0 then
409 v.fatal "FFI Error: Failed to compile C code using `{cmd}`"