backends.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. ================================
  2. Nim Backend Integration
  3. ================================
  4. :Author: Puppet Master
  5. :Version: |nimversion|
  6. .. contents::
  7. "Heresy grows from idleness." -- Unknown.
  8. Introduction
  9. ============
  10. The `Nim Compiler User Guide <nimc.html>`_ documents the typical
  11. compiler invocation, using the ``compile`` or ``c`` command to transform a
  12. ``.nim`` file into one or more ``.c`` files which are then compiled with the
  13. platform's C compiler into a static binary. However there are other commands
  14. to compile to C++, Objective-C or JavaScript. This document tries to
  15. concentrate in a single place all the backend and interfacing options.
  16. The Nim compiler supports mainly two backend families: the C, C++ and
  17. Objective-C targets and the JavaScript target. `The C like targets
  18. <#backends-the-c-like-targets>`_ creates source files which can be compiled
  19. into a library or a final executable. `The JavaScript target
  20. <#backends-the-javascript-target>`_ can generate a ``.js`` file which you
  21. reference from an HTML file or create a `standalone nodejs program
  22. <http://nodejs.org>`_.
  23. On top of generating libraries or standalone applications, Nim offers
  24. bidirectional interfacing with the backend targets through generic and
  25. specific pragmas.
  26. Backends
  27. ========
  28. The C like targets
  29. ------------------
  30. The commands to compile to either C, C++ or Objective-C are:
  31. //compileToC, cc compile project with C code generator
  32. //compileToCpp, cpp compile project to C++ code
  33. //compileToOC, objc compile project to Objective C code
  34. The most significant difference between these commands is that if you look
  35. into the ``nimcache`` directory you will find ``.c``, ``.cpp`` or ``.m``
  36. files, other than that all of them will produce a native binary for your
  37. project. This allows you to take the generated code and place it directly
  38. into a project using any of these languages. Here are some typical command
  39. line invocations::
  40. $ nim c hallo.nim
  41. $ nim cpp hallo.nim
  42. $ nim objc hallo.nim
  43. The compiler commands select the target backend, but if needed you can
  44. `specify additional switches for cross compilation
  45. <nimc.html#cross-compilation>`_ to select the target CPU, operative system
  46. or compiler/linker commands.
  47. The JavaScript target
  48. ---------------------
  49. Nim can also generate `JavaScript`:idx: code through the ``js`` command.
  50. Nim targets JavaScript 1.5 which is supported by any widely used browser.
  51. Since JavaScript does not have a portable means to include another module,
  52. Nim just generates a long ``.js`` file.
  53. Features or modules that the JavaScript platform does not support are not
  54. available. This includes:
  55. * manual memory management (``alloc``, etc.)
  56. * casting and other unsafe operations (``cast`` operator, ``zeroMem``, etc.)
  57. * file management
  58. * most modules of the standard library
  59. * proper 64 bit integer arithmetic
  60. * unsigned integer arithmetic
  61. However, the modules `strutils <strutils.html>`_, `math <math.html>`_, and
  62. `times <times.html>`_ are available! To access the DOM, use the `dom
  63. <dom.html>`_ module that is only available for the JavaScript platform.
  64. To compile a Nim module into a ``.js`` file use the ``js`` command; the
  65. default is a ``.js`` file that is supposed to be referenced in an ``.html``
  66. file. However, you can also run the code with `nodejs`:idx:
  67. (`<http://nodejs.org>`_)::
  68. nim js -d:nodejs -r examples/hallo.nim
  69. Interfacing
  70. ===========
  71. Nim offers bidirectional interfacing with the target backend. This means
  72. that you can call backend code from Nim and Nim code can be called by
  73. the backend code. Usually the direction of which calls which depends on your
  74. software architecture (is Nim your main program or is Nim providing a
  75. component?).
  76. Nim code calling the backend
  77. ----------------------------
  78. Nim code can interface with the backend through the `Foreign function
  79. interface <manual.html#foreign-function-interface>`_ mainly through the
  80. `importc pragma <manual.html#importc-pragma>`_. The ``importc`` pragma is the
  81. *generic* way of making backend symbols available in Nim and is available
  82. in all the target backends (JavaScript too). The C++ or Objective-C backends
  83. have their respective `ImportCpp <manual.html#implementation-specific-pragmas-importcpp-pragma>`_ and
  84. `ImportObjC <manual.html#implementation-specific-pragmas-importobjc-pragma>`_ pragmas to call methods from
  85. classes.
  86. Whenever you use any of these pragmas you need to integrate native code into
  87. your final binary. In the case of JavaScript this is no problem at all, the
  88. same html file which hosts the generated JavaScript will likely provide other
  89. JavaScript functions which you are importing with ``importc``.
  90. However, for the C like targets you need to link external code either
  91. statically or dynamically. The preferred way of integrating native code is to
  92. use dynamic linking because it allows you to compile Nim programs without
  93. the need for having the related development libraries installed. This is done
  94. through the `dynlib pragma for import
  95. <manual.html#dynlib-pragma-for-import>`_, though more specific control can be
  96. gained using the `dynlib module <dynlib.html>`_.
  97. The `dynlibOverride <nimc.html#dynliboverride>`_ command line switch allows
  98. to avoid dynamic linking if you need to statically link something instead.
  99. Nim wrappers designed to statically link source files can use the `compile
  100. pragma <nimc.html#compile-pragma>`_ if there are few sources or providing
  101. them along the Nim code is easier than using a system library. Libraries
  102. installed on the host system can be linked in with the `PassL pragma
  103. <nimc.html#passl-pragma>`_.
  104. To wrap native code, take a look at the `c2nim tool <https://nim-lang.org/docs/c2nim.html>`_ which helps
  105. with the process of scanning and transforming header files into a Nim
  106. interface.
  107. C invocation example
  108. ~~~~~~~~~~~~~~~~~~~~
  109. Create a ``logic.c`` file with the following content:
  110. .. code-block:: c
  111. int addTwoIntegers(int a, int b)
  112. {
  113. return a + b;
  114. }
  115. Create a ``calculator.nim`` file with the following content:
  116. .. code-block:: nim
  117. {.compile: "logic.c".}
  118. proc addTwoIntegers(a, b: cint): cint {.importc.}
  119. when isMainModule:
  120. echo addTwoIntegers(3, 7)
  121. With these two files in place, you can run ``nim c -r calculator.nim`` and
  122. the Nim compiler will compile the ``logic.c`` file in addition to
  123. ``calculator.nim`` and link both into an executable, which outputs ``10`` when
  124. run. Another way to link the C file statically and get the same effect would
  125. be remove the line with the ``compile`` pragma and run the following typical
  126. Unix commands::
  127. $ gcc -c logic.c
  128. $ ar rvs mylib.a logic.o
  129. $ nim c --passL:mylib.a -r calculator.nim
  130. Just like in this example we pass the path to the ``mylib.a`` library (and we
  131. could as well pass ``logic.o``) we could be passing switches to link any other
  132. static C library.
  133. JavaScript invocation example
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  135. Create a ``host.html`` file with the following content:
  136. .. code-block::
  137. <html><body>
  138. <script type="text/javascript">
  139. function addTwoIntegers(a, b)
  140. {
  141. return a + b;
  142. }
  143. </script>
  144. <script type="text/javascript" src="calculator.js"></script>
  145. </body></html>
  146. Create a ``calculator.nim`` file with the following content (or reuse the one
  147. from the previous section):
  148. .. code-block:: nim
  149. proc addTwoIntegers(a, b: int): int {.importc.}
  150. when isMainModule:
  151. echo addTwoIntegers(3, 7)
  152. Compile the Nim code to JavaScript with ``nim js -o:calculator.js
  153. calculator.nim`` and open ``host.html`` in a browser. If the browser supports
  154. javascript, you should see the value ``10`` in the browser's console. Use the
  155. `dom module <dom.html>`_ for specific DOM querying and modification procs
  156. or take a look at `karax <https://github.com/pragmagic/karax>`_ for how to
  157. develop browser based applications.
  158. Backend code calling Nim
  159. ------------------------
  160. Backend code can interface with Nim code exposed through the `exportc
  161. pragma <manual.html#exportc-pragma>`_. The ``exportc`` pragma is the *generic*
  162. way of making Nim symbols available to the backends. By default the Nim
  163. compiler will mangle all the Nim symbols to avoid any name collision, so
  164. the most significant thing the ``exportc`` pragma does is maintain the Nim
  165. symbol name, or if specified, use an alternative symbol for the backend in
  166. case the symbol rules don't match.
  167. The JavaScript target doesn't have any further interfacing considerations
  168. since it also has garbage collection, but the C targets require you to
  169. initialize Nim's internals, which is done calling a ``NimMain`` function.
  170. Also, C code requires you to specify a forward declaration for functions or
  171. the compiler will assume certain types for the return value and parameters
  172. which will likely make your program crash at runtime.
  173. The Nim compiler can generate a C interface header through the ``--header``
  174. command line switch. The generated header will contain all the exported
  175. symbols and the ``NimMain`` proc which you need to call before any other
  176. Nim code.
  177. Nim invocation example from C
  178. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  179. Create a ``fib.nim`` file with the following content:
  180. .. code-block:: nim
  181. proc fib(a: cint): cint {.exportc.} =
  182. if a <= 2:
  183. result = 1
  184. else:
  185. result = fib(a - 1) + fib(a - 2)
  186. Create a ``maths.c`` file with the following content:
  187. .. code-block:: c
  188. #include "fib.h"
  189. #include <stdio.h>
  190. int main(void)
  191. {
  192. NimMain();
  193. for (int f = 0; f < 10; f++)
  194. printf("Fib of %d is %d\n", f, fib(f));
  195. return 0;
  196. }
  197. Now you can run the following Unix like commands to first generate C sources
  198. form the Nim code, then link them into a static binary along your main C
  199. program::
  200. $ nim c --noMain --noLinking --header:fib.h fib.nim
  201. $ gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c
  202. The first command runs the Nim compiler with three special options to avoid
  203. generating a ``main()`` function in the generated files, avoid linking the
  204. object files into a final binary, and explicitly generate a header file for C
  205. integration. All the generated files are placed into the ``nimcache``
  206. directory. That's why the next command compiles the ``maths.c`` source plus
  207. all the ``.c`` files form ``nimcache``. In addition to this path, you also
  208. have to tell the C compiler where to find Nim's ``nimbase.h`` header file.
  209. Instead of depending on the generation of the individual ``.c`` files you can
  210. also ask the Nim compiler to generate a statically linked library::
  211. $ nim c --app:staticLib --noMain --header fib.nim
  212. $ gcc -o m -Inimcache -Ipath/to/nim/lib libfib.nim.a maths.c
  213. The Nim compiler will handle linking the source files generated in the
  214. ``nimcache`` directory into the ``libfib.nim.a`` static library, which you can
  215. then link into your C program. Note that these commands are generic and will
  216. vary for each system. For instance, on Linux systems you will likely need to
  217. use ``-ldl`` too to link in required dlopen functionality.
  218. Nim invocation example from JavaScript
  219. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  220. Create a ``mhost.html`` file with the following content:
  221. .. code-block::
  222. <html><body>
  223. <script type="text/javascript" src="fib.js"></script>
  224. <script type="text/javascript">
  225. alert("Fib for 9 is " + fib(9));
  226. </script>
  227. </body></html>
  228. Create a ``fib.nim`` file with the following content (or reuse the one
  229. from the previous section):
  230. .. code-block:: nim
  231. proc fib(a: cint): cint {.exportc.} =
  232. if a <= 2:
  233. result = 1
  234. else:
  235. result = fib(a - 1) + fib(a - 2)
  236. Compile the Nim code to JavaScript with ``nim js -o:fib.js fib.nim`` and
  237. open ``mhost.html`` in a browser. If the browser supports javascript, you
  238. should see an alert box displaying the text ``Fib for 9 is 34``. As mentioned
  239. earlier, JavaScript doesn't require an initialisation call to ``NimMain`` or
  240. similar function and you can call the exported Nim proc directly.
  241. Nimcache naming logic
  242. ---------------------
  243. The `nimcache`:idx: directory is generated during compilation and will hold
  244. either temporary or final files depending on your backend target. The default
  245. name for the directory depends on the used backend and on your OS but you can
  246. use the ``--nimcache`` `compiler switch <nimc.html#command-line-switches>`_ to
  247. change it.
  248. Nimcache and C like targets
  249. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  250. The C like backends will place their temporary ``.c``, ``.cpp`` or ``.m`` files
  251. in the ``nimcache`` directory. The naming of these files follows the pattern
  252. ``nimblePackageName_`` + ``nimSource``:
  253. * Filenames for modules imported from `nimble packages
  254. <https://github.com/nim-lang/nimble>`_ will end up with
  255. ``nimblePackageName_module.c``. For example, if you import the
  256. ``argument_parser`` module from the same name nimble package you
  257. will end up with a ``argument_parser_argument_parser.c`` file
  258. under ``nimcache``. The name of the nimble package comes from the
  259. ``proj.nimble`` file, the actual contents are not read by the
  260. compiler.
  261. * Filenames for non nimble packages (like your project) will be
  262. renamed from ``.nim`` to have the extension of your target backend
  263. (from now on ``.c`` for these examples), but otherwise nothing
  264. else will change. This will quickly break if your project consists
  265. of a main ``proj.nim`` file which includes a ``utils/proj.nim``
  266. file: both ``proj.nim`` files will generate the same name ``proj.c``
  267. output in the ``nimcache`` directory overwriting themselves!
  268. * Filenames for modules found in the standard library will be named
  269. ``stdlib_module.c``. Unless you are doing something special, you
  270. will end up with at least ``stdlib_system.c``, since the `system
  271. module <system.html>`_ is always imported automatically. Same for
  272. the `hashes module <hashes.html>`_ which will be named
  273. ``stdlib_hashes.c``. The ``stdlib_`` prefix comes from the *fake*
  274. ``lib/stdlib.nimble`` file.
  275. To find the name of a nimble package the compiler searches for a ``*.nimble``
  276. file in the parent directory hierarchy of whatever module you are compiling.
  277. Even if you are in a subdirectory of your project, a parent ``*.nimble`` file
  278. will influence the naming of the nimcache name. This means that on Unix systems
  279. creating the file ``~/foo.nimble`` will automatically prefix all nimcache files
  280. not part of another package with the string ``foo_``.
  281. Nimcache and the Javascript target
  282. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  283. Unless you explicitly use the ``-o:filename.js`` switch as mentioned in the
  284. previous examples, the compiler will create a ``filename.js`` file in the
  285. ``nimcache`` directory using the name of your input nim file. There are no
  286. other temporary files generated, the output is always a single self contained
  287. ``.js`` file.
  288. Memory management
  289. =================
  290. In the previous sections the ``NimMain()`` function reared its head. Since
  291. JavaScript already provides automatic memory management, you can freely pass
  292. objects between the two language without problems. In C and derivate languages
  293. you need to be careful about what you do and how you share memory. The
  294. previous examples only dealt with simple scalar values, but passing a Nim
  295. string to C, or reading back a C string in Nim already requires you to be
  296. aware of who controls what to avoid crashing.
  297. Strings and C strings
  298. ---------------------
  299. The manual mentions that `Nim strings are implicitly convertible to
  300. cstrings <manual.html#cstring-type>`_ which makes interaction usually
  301. painless. Most C functions accepting a Nim string converted to a
  302. ``cstring`` will likely not need to keep this string around and by the time
  303. they return the string won't be needed any more. However, for the rare cases
  304. where a Nim string has to be preserved and made available to the C backend
  305. as a ``cstring``, you will need to manually prevent the string data from being
  306. freed with `GC_ref <system.html#GC_ref>`_ and `GC_unref
  307. <system.html#GC_unref>`_.
  308. A similar thing happens with C code invoking Nim code which returns a
  309. ``cstring``. Consider the following proc:
  310. .. code-block:: nim
  311. proc gimme(): cstring {.exportc.} =
  312. result = "Hey there C code! " & $random(100)
  313. Since Nim's garbage collector is not aware of the C code, once the
  314. ``gimme`` proc has finished it can reclaim the memory of the ``cstring``.
  315. However, from a practical standpoint, the C code invoking the ``gimme``
  316. function directly will be able to use it since Nim's garbage collector has
  317. not had a chance to run *yet*. This gives you enough time to make a copy for
  318. the C side of the program, as calling any further Nim procs *might* trigger
  319. garbage collection making the previously returned string garbage. Or maybe you
  320. are `yourself triggering the collection <gc.html>`_.
  321. Custom data types
  322. -----------------
  323. Just like strings, custom data types that are to be shared between Nim and
  324. the backend will need careful consideration of who controls who. If you want
  325. to hand a Nim reference to C code, you will need to use `GC_ref
  326. <system.html#GC_ref>`_ to mark the reference as used, so it does not get
  327. freed. And for the C backend you will need to expose the `GC_unref
  328. <system.html#GC_unref>`_ proc to clean up this memory when it is not required
  329. any more.
  330. Again, if you are wrapping a library which *mallocs* and *frees* data
  331. structures, you need to expose the appropriate *free* function to Nim so
  332. you can clean it up. And of course, once cleaned you should avoid accessing it
  333. from Nim (or C for that matter). Typically C data structures have their own
  334. ``malloc_structure`` and ``free_structure`` specific functions, so wrapping
  335. these for the Nim side should be enough.
  336. Thread coordination
  337. -------------------
  338. When the ``NimMain()`` function is called Nim initializes the garbage
  339. collector to the current thread, which is usually the main thread of your
  340. application. If your C code later spawns a different thread and calls Nim
  341. code, the garbage collector will fail to work properly and you will crash.
  342. As long as you don't use the threadvar emulation Nim uses native thread
  343. variables, of which you get a fresh version whenever you create a thread. You
  344. can then attach a GC to this thread via
  345. .. code-block:: nim
  346. system.setupForeignThreadGc()
  347. It is **not** safe to disable the garbage collector and enable it after the
  348. call from your background thread even if the code you are calling is short
  349. lived.
  350. Before the thread exits, you should tear down the thread's GC to prevent memory
  351. leaks by calling
  352. .. code-block:: nim
  353. system.tearDownForeignThreadGc()