Merge remote-tracking branch 'origin/master' into init_auto
[nit.git] / src / interpreter / dynamic_loading_ffi / on_demand_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # Compiles extern code within a module to a static library, as needed
16 module on_demand_compiler
17
18 import modelbuilder
19 import c_tools
20 import nitni
21 import ffi
22 import naive_interpreter
23 import pkgconfig
24 import debugger_socket # To linearize `ToolContext::init`
25
26 redef class ToolContext
27
28 # --compile-dir
29 var opt_compile_dir = new OptionString("Directory used to generate temporary files", "--compile-dir")
30
31 init do option_context.add_option opt_compile_dir
32 end
33
34 redef class AMethPropdef
35 # Does this method definition use the FFI and is it supported by the interpreter?
36 #
37 # * Must use the nested foreign code block of the FFI.
38 # * Must not have callbacks.
39 # * Must be implemented in C.
40 # * Must not have a parameter or return typed with a Nit standard class.
41 fun supported_by_dynamic_ffi: Bool
42 do
43 # If the user specfied `is light_ffi`, it must be supported
44 var nats = get_annotations("light_ffi")
45 if nats.not_empty then return true
46
47 var n_extern_code_block = n_extern_code_block
48 if not (n_extern_calls == null and n_extern_code_block != null and
49 n_extern_code_block.is_c) then return false
50
51 for mparam in mpropdef.msignature.mparameters do
52 if not mparam.mtype.is_cprimitive then
53 return false
54 end
55 end
56
57 var return_mtype = mpropdef.msignature.return_mtype
58 if return_mtype != null and not return_mtype.is_cprimitive then
59 return false
60 end
61
62 return true
63 end
64 end
65
66 redef class NaiveInterpreter
67 redef fun start(mainmodule)
68 do
69 super
70
71 # Delete temporary files
72 var compile_dir = compile_dir
73 if compile_dir.file_exists then compile_dir.rmdir
74 end
75
76 # Where to store generated C and extracted code
77 private var compile_dir: String is lazy do
78 # Prioritize the user supplied directory
79 var opt = modelbuilder.toolcontext.opt_compile_dir.value
80 if opt != null then return opt
81 return "/tmp/niti_ffi_{process_id}"
82 end
83
84 # Identifier for this process, unique between running interpreters
85 private fun process_id: Int `{ return getpid(); `}
86
87 # Path of the compiled foreign code library
88 #
89 # TODO change the ".so" extension per platform.
90 fun foreign_code_lib_path(mmodule: MModule): String
91 do
92 return compile_dir / mmodule.c_name + ".so"
93 end
94
95 # External compiler used to generate the foreign code library
96 private var c_compiler = "gcc"
97 end
98
99 redef class AModule
100
101 # Compile user FFI code and a standardized API into a `.so` file
102 #
103 # Returns `true` on success.
104 fun compile_foreign_lib(v: NaiveInterpreter): Bool
105 do
106 var mmodule = mmodule
107 assert mmodule != null
108
109 var compile_dir = v.compile_dir
110 var foreign_code_lib_path = v.foreign_code_lib_path(mmodule)
111
112 if not compile_dir.file_exists then compile_dir.mkdir(0o700)
113
114 # Compile the common FFI part
115 ensure_compile_ffi_wrapper
116 for mclassdef in mmodule.mclassdefs do for mpropdef in mclassdef.mpropdefs do
117 var anode = v.modelbuilder.mpropdef2node(mpropdef)
118 if mpropdef isa MMethodDef and anode isa AMethPropdef and anode.supported_by_dynamic_ffi then
119 anode.compile_ffi_method(mmodule)
120 end
121 end
122 mmodule.finalize_ffi_wrapper(compile_dir, mmodule)
123
124 # Compile the standard API and its implementation for the .so file
125 var ccu = compile_foreign_lib_api(compile_dir)
126
127 var srcs = [for file in ccu.files do new ExternCFile(file, ""): ExternFile]
128 srcs.add_all mmodule.ffi_files
129
130 # Compiler options specific to this module
131 var ldflags = mmodule.ldflags[""].join(" ")
132
133 # Protect pkg-config
134 var pkgconfigs = mmodule.pkgconfigs
135 var pkg_command = ""
136 if not pkgconfigs.is_empty then
137 var cmd = "which pkg-config >/dev/null"
138 if system(cmd) != 0 then
139 v.fatal "FFI Error: Command `pkg-config` not found. Please install it"
140 return false
141 end
142
143 for p in pkgconfigs do
144 cmd = "pkg-config --exists '{p}'"
145 if system(cmd) != 0 then
146 v.fatal "FFI Error: package {p} is not found by `pkg-config`. Please install it."
147 return false
148 end
149 end
150
151 pkg_command = "`pkg-config --cflags --libs {pkgconfigs.join(" ")}`"
152 end
153
154 # Compile each source file to an object file (or equivalent)
155 var object_files = new Array[String]
156 for f in srcs do
157 f.compile(v, mmodule, object_files)
158 end
159
160 # Link everything in a shared library
161 var cmd = "{v.c_compiler} -Wall -shared -o {foreign_code_lib_path} {object_files.join(" ")} {ldflags} {pkg_command}"
162 if system(cmd) != 0 then
163 v.fatal "FFI Error: Failed to link native code using `{cmd}`"
164 return false
165 end
166
167 return true
168 end
169
170 # Compile the standard API of the `.so` file
171 #
172 # * The shared structure `nit_call_arg`.
173 # * Standardized implementation functions entrypoints that relay calls
174 # to the FFI implementation functions.
175 private fun compile_foreign_lib_api(compdir: String): CCompilationUnit
176 do
177 var mmodule = mmodule
178 assert mmodule != null
179
180 # ready extern code compiler
181 var ecc = new CCompilationUnit
182
183 ecc.body_decl.add """
184
185 #include <string.h>
186 #include <stdio.h>
187 #include <inttypes.h>
188
189 // C structure behind `CallArg` from the interpreter
190 typedef union nit_call_arg {
191 long value_Int;
192 int value_Bool;
193 uint32_t value_Char;
194 uint8_t value_Byte;
195 int8_t value_Int8;
196 int16_t value_Int16;
197 uint16_t value_UInt16;
198 int32_t value_Int32;
199 uint32_t value_UInt32;
200 double value_Float;
201 void* value_Pointer;
202 } nit_call_arg;
203
204 """
205
206 # types
207 var used_types = collect_mtypes
208 for t in used_types do
209 if not t.is_cprimitive then
210 ecc.header_c_types.add "typedef void* {t.cname};\n"
211 end
212 end
213
214 # TODO callbacks & casts
215
216 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
217 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
218 npropdef.mpropdef.compile_foreign_code_entry ecc
219 end
220 end
221
222 ecc.write_as_foreign_lib_api(mmodule, compdir)
223
224 return ecc
225 end
226
227 # Collect all `MType` use in extern methods within this module
228 private fun collect_mtypes: Set[MType]
229 do
230 var used_types = new HashSet[MType]
231
232 # collect callbacks
233 for nclassdef in n_classdefs do for npropdef in nclassdef.n_propdefs do
234 if npropdef isa AMethPropdef and npropdef.supported_by_dynamic_ffi then
235 var fcs = npropdef.foreign_callbacks
236 used_types.add_all fcs.types
237 end
238 end
239
240 return used_types
241 end
242 end
243
244 redef class CCompilationUnit
245 # Write this compilation unit as the API of a foreign code library
246 private fun write_as_foreign_lib_api(mmodule: MModule, compdir: String)
247 do
248 # The FFI expects the support header to end with `._nitni.h`
249 var base_name = mmodule.c_name + "._nitni"
250 var guard = mmodule.c_name.to_s.to_upper + "_API_H"
251 var header_comment = """
252 /*
253 Public API to foreign code of the Nit module {{{mmodule.name}}}
254 */
255 """
256
257 # Header file
258 var h_file = base_name+".h"
259 var stream = new FileWriter.open(compdir/h_file)
260 stream.write header_comment
261 stream.write """
262 #ifndef {{{guard}}}
263 #define {{{guard}}}
264 """
265 compile_header_core stream
266 stream.write """
267
268 #endif
269 """
270 stream.close
271
272 # Body file
273 var c_file = base_name+".c"
274 stream = new FileWriter.open(compdir/c_file)
275 stream.write header_comment
276 stream.write """
277 #include "{{{h_file}}}"
278 """
279 compile_body_core stream
280 stream.close
281
282 # Only the C files needs compiling
283 files.add compdir / c_file
284 end
285 end
286
287 redef class MMethodDef
288 # Name of the entry point to the implementation function in the foreign lib
289 fun foreign_lib_entry_cname: String do return "entry__{cname}"
290
291 # Compile the standardized entry point as part of the foreign lib API
292 private fun compile_foreign_code_entry(ecc: CCompilationUnit)
293 do
294 var msignature = msignature
295 if msignature == null then return
296
297 # Return type
298 var return_mtype = msignature.return_mtype
299 if mproperty.is_init then return_mtype = mclassdef.mclass.mclass_type
300
301 var c_return_type
302 if return_mtype != null then
303 c_return_type = return_mtype.cname_blind
304 else c_return_type = "void"
305
306 var is_init = mproperty.is_init
307
308 # Params
309 var params = new Array[String]
310 if not is_init then params.add mclassdef.mclass.mclass_type.cname_blind
311 for param in msignature.mparameters do params.add param.mtype.cname_blind
312
313 # Declare the implementation function as extern
314 var impl_cname = mproperty.build_cname(mclassdef.bound_mtype,
315 mclassdef.mmodule, "___impl", long_signature)
316 ecc.body_decl.add "extern {c_return_type} {impl_cname}({params.join(", ")});\n"
317
318 # Declare the entry function
319 var foreign_lib_entry_cname = "int {foreign_lib_entry_cname}(int argc, nit_call_arg *argv, nit_call_arg *result)"
320 var fc = new CFunction(foreign_lib_entry_cname)
321
322 # Check argument count on the library side
323 #
324 # This may detect inconsistencies between the interpreter and the generated code.
325 var expected_argc = msignature.arity
326 if not is_init then expected_argc += 1
327
328 fc.exprs.add """
329 if (argc != {{{expected_argc}}}) {
330 printf("Invalid argument count in `{{{mproperty.full_name}}}`, expected %d, got %d.\\n",
331 argc, {{{expected_argc}}});
332 return 1;
333 }
334 """
335
336 # Unpack and prepare args for the user code
337 var k = 0
338 var args_for_call = new Array[String]
339 if not is_init then
340 var mtype = mclassdef.mclass.mclass_type
341 var arg_name = "arg___self"
342
343 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
344 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
345 args_for_call.add arg_name
346
347 k += 1
348 end
349 for param in msignature.mparameters do
350 var mtype = param.mtype
351 var arg_name = "arg__"+param.name
352
353 fc.decls.add " {mtype.cname_blind} {arg_name};\n"
354 fc.exprs.add " {arg_name} = argv[{k}].{mtype.call_arg_field};\n"
355 args_for_call.add arg_name
356
357 k += 1
358 end
359
360 # Call implementation function
361 var args_compressed = args_for_call.join(", ")
362 var method_call = "{impl_cname}({args_compressed})"
363 if return_mtype != null then
364 fc.decls.add """
365 {{{return_mtype.cname_blind}}} return_value;
366 """
367 fc.exprs.add """
368 return_value = {{{method_call}}};
369 result->{{{return_mtype.call_arg_field}}} = return_value;
370 """
371 else
372 fc.exprs.add " {method_call};\n"
373 end
374
375 fc.exprs.add " return 0;\n"
376
377 ecc.add_exported_function fc
378 end
379 end
380
381 redef class MType
382 # The interpreter FFI use `void*` to represent intern data types
383 redef fun cname_blind do return "void*"
384
385 # Field to store this type in the C structure `nit_call_arg`
386 private fun call_arg_field: String do return "value_Pointer"
387 end
388
389 redef class MClassType
390 redef fun call_arg_field
391 do
392 if is_cprimitive and mclass.kind != extern_kind then
393 return "value_{name}"
394 else return super
395 end
396 end
397
398 redef class ExternFile
399 # Compile this source file
400 private fun compile(v: NaiveInterpreter, mmodule: MModule,
401 object_files: Array[String]): Bool is abstract
402 end
403
404 redef class ExternCFile
405 redef fun compile(v, mmodule, object_files)
406 do
407 var compile_dir = v.compile_dir
408 var cflags = mmodule.cflags[""].join(" ")
409 var obj = compile_dir / filename.basename(".c") + ".o"
410
411 var cmd = "{v.c_compiler} -Wall -c -fPIC -I {compile_dir} -g -o {obj} {filename} {cflags}"
412 if sys.system(cmd) != 0 then
413 v.fatal "FFI Error: Failed to compile C code using `{cmd}`"
414 return false
415 end
416
417 object_files.add obj
418 return true
419 end
420 end