backends.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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#foreign-function-interface-importc-pragma>`_.
  81. The ``importc`` pragma is the *generic* way of making backend symbols available
  82. in Nim and is available in all the target backends (JavaScript too). The C++
  83. or Objective-C backends have their respective `ImportCpp
  84. <manual.html#implementation-specific-pragmas-importcpp-pragma>`_ and
  85. `ImportObjC <manual.html#implementation-specific-pragmas-importobjc-pragma>`_
  86. pragmas to call methods from classes.
  87. Whenever you use any of these pragmas you need to integrate native code into
  88. your final binary. In the case of JavaScript this is no problem at all, the
  89. same html file which hosts the generated JavaScript will likely provide other
  90. JavaScript functions which you are importing with ``importc``.
  91. However, for the C like targets you need to link external code either
  92. statically or dynamically. The preferred way of integrating native code is to
  93. use dynamic linking because it allows you to compile Nim programs without
  94. the need for having the related development libraries installed. This is done
  95. through the `dynlib pragma for import
  96. <manual.html#foreign-function-interface-dynlib-pragma-for-import>`_, though
  97. more specific control can be gained using the `dynlib module <dynlib.html>`_.
  98. The `dynlibOverride <nimc.html#dynliboverride>`_ command line switch allows
  99. to avoid dynamic linking if you need to statically link something instead.
  100. Nim wrappers designed to statically link source files can use the `compile
  101. pragma <manual.html#implementation-specific-pragmas-compile-pragma>`_ if
  102. there are few sources or providing them along the Nim code is easier than using
  103. a system library. Libraries installed on the host system can be linked in with
  104. the `PassL pragma <manual.html#implementation-specific-pragmas-passl-pragma>`_.
  105. To wrap native code, take a look at the `c2nim tool <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ which helps
  106. with the process of scanning and transforming header files into a Nim
  107. interface.
  108. C invocation example
  109. ~~~~~~~~~~~~~~~~~~~~
  110. Create a ``logic.c`` file with the following content:
  111. .. code-block:: c
  112. int addTwoIntegers(int a, int b)
  113. {
  114. return a + b;
  115. }
  116. Create a ``calculator.nim`` file with the following content:
  117. .. code-block:: nim
  118. {.compile: "logic.c".}
  119. proc addTwoIntegers(a, b: cint): cint {.importc.}
  120. when isMainModule:
  121. echo addTwoIntegers(3, 7)
  122. With these two files in place, you can run ``nim c -r calculator.nim`` and
  123. the Nim compiler will compile the ``logic.c`` file in addition to
  124. ``calculator.nim`` and link both into an executable, which outputs ``10`` when
  125. run. Another way to link the C file statically and get the same effect would
  126. be remove the line with the ``compile`` pragma and run the following typical
  127. Unix commands::
  128. $ gcc -c logic.c
  129. $ ar rvs mylib.a logic.o
  130. $ nim c --passL:mylib.a -r calculator.nim
  131. Just like in this example we pass the path to the ``mylib.a`` library (and we
  132. could as well pass ``logic.o``) we could be passing switches to link any other
  133. static C library.
  134. JavaScript invocation example
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. Create a ``host.html`` file with the following content:
  137. .. code-block::
  138. <html><body>
  139. <script type="text/javascript">
  140. function addTwoIntegers(a, b)
  141. {
  142. return a + b;
  143. }
  144. </script>
  145. <script type="text/javascript" src="calculator.js"></script>
  146. </body></html>
  147. Create a ``calculator.nim`` file with the following content (or reuse the one
  148. from the previous section):
  149. .. code-block:: nim
  150. proc addTwoIntegers(a, b: int): int {.importc.}
  151. when isMainModule:
  152. echo addTwoIntegers(3, 7)
  153. Compile the Nim code to JavaScript with ``nim js -o:calculator.js
  154. calculator.nim`` and open ``host.html`` in a browser. If the browser supports
  155. javascript, you should see the value ``10`` in the browser's console. Use the
  156. `dom module <dom.html>`_ for specific DOM querying and modification procs
  157. or take a look at `karax <https://github.com/pragmagic/karax>`_ for how to
  158. develop browser based applications.
  159. Backend code calling Nim
  160. ------------------------
  161. Backend code can interface with Nim code exposed through the `exportc
  162. pragma <manual.html#foreign-function-interface-exportc-pragma>`_. The
  163. ``exportc`` pragma is the *generic* way of making Nim symbols available to
  164. the backends. By default the Nim compiler will mangle all the Nim symbols to
  165. avoid any name collision, so the most significant thing the ``exportc`` pragma
  166. does is maintain the Nim symbol name, or if specified, use an alternative
  167. symbol for the backend in case the symbol rules don't match.
  168. The JavaScript target doesn't have any further interfacing considerations
  169. since it also has garbage collection, but the C targets require you to
  170. initialize Nim's internals, which is done calling a ``NimMain`` function.
  171. Also, C code requires you to specify a forward declaration for functions or
  172. the compiler will assume certain types for the return value and parameters
  173. which will likely make your program crash at runtime.
  174. The Nim compiler can generate a C interface header through the ``--header``
  175. command line switch. The generated header will contain all the exported
  176. symbols and the ``NimMain`` proc which you need to call before any other
  177. Nim code.
  178. Nim invocation example from C
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. Create a ``fib.nim`` file with the following content:
  181. .. code-block:: nim
  182. proc fib(a: cint): cint {.exportc.} =
  183. if a <= 2:
  184. result = 1
  185. else:
  186. result = fib(a - 1) + fib(a - 2)
  187. Create a ``maths.c`` file with the following content:
  188. .. code-block:: c
  189. #include "fib.h"
  190. #include <stdio.h>
  191. int main(void)
  192. {
  193. NimMain();
  194. for (int f = 0; f < 10; f++)
  195. printf("Fib of %d is %d\n", f, fib(f));
  196. return 0;
  197. }
  198. Now you can run the following Unix like commands to first generate C sources
  199. form the Nim code, then link them into a static binary along your main C
  200. program::
  201. $ nim c --noMain --noLinking --header:fib.h fib.nim
  202. $ gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c
  203. The first command runs the Nim compiler with three special options to avoid
  204. generating a ``main()`` function in the generated files, avoid linking the
  205. object files into a final binary, and explicitly generate a header file for C
  206. integration. All the generated files are placed into the ``nimcache``
  207. directory. That's why the next command compiles the ``maths.c`` source plus
  208. all the ``.c`` files form ``nimcache``. In addition to this path, you also
  209. have to tell the C compiler where to find Nim's ``nimbase.h`` header file.
  210. Instead of depending on the generation of the individual ``.c`` files you can
  211. also ask the Nim compiler to generate a statically linked library::
  212. $ nim c --app:staticLib --noMain --header fib.nim
  213. $ gcc -o m -Inimcache -Ipath/to/nim/lib libfib.nim.a maths.c
  214. The Nim compiler will handle linking the source files generated in the
  215. ``nimcache`` directory into the ``libfib.nim.a`` static library, which you can
  216. then link into your C program. Note that these commands are generic and will
  217. vary for each system. For instance, on Linux systems you will likely need to
  218. use ``-ldl`` too to link in required dlopen functionality.
  219. Nim invocation example from JavaScript
  220. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  221. Create a ``mhost.html`` file with the following content:
  222. .. code-block::
  223. <html><body>
  224. <script type="text/javascript" src="fib.js"></script>
  225. <script type="text/javascript">
  226. alert("Fib for 9 is " + fib(9));
  227. </script>
  228. </body></html>
  229. Create a ``fib.nim`` file with the following content (or reuse the one
  230. from the previous section):
  231. .. code-block:: nim
  232. proc fib(a: cint): cint {.exportc.} =
  233. if a <= 2:
  234. result = 1
  235. else:
  236. result = fib(a - 1) + fib(a - 2)
  237. Compile the Nim code to JavaScript with ``nim js -o:fib.js fib.nim`` and
  238. open ``mhost.html`` in a browser. If the browser supports javascript, you
  239. should see an alert box displaying the text ``Fib for 9 is 34``. As mentioned
  240. earlier, JavaScript doesn't require an initialisation call to ``NimMain`` or
  241. similar function and you can call the exported Nim proc directly.
  242. Nimcache naming logic
  243. ---------------------
  244. The `nimcache`:idx: directory is generated during compilation and will hold
  245. either temporary or final files depending on your backend target. The default
  246. name for the directory depends on the used backend and on your OS but you can
  247. use the ``--nimcache`` `compiler switch
  248. <nimc.html#compiler-usage-command-line-switches>`_ to change it.
  249. Memory management
  250. =================
  251. In the previous sections the ``NimMain()`` function reared its head. Since
  252. JavaScript already provides automatic memory management, you can freely pass
  253. objects between the two language without problems. In C and derivate languages
  254. you need to be careful about what you do and how you share memory. The
  255. previous examples only dealt with simple scalar values, but passing a Nim
  256. string to C, or reading back a C string in Nim already requires you to be
  257. aware of who controls what to avoid crashing.
  258. Strings and C strings
  259. ---------------------
  260. The manual mentions that `Nim strings are implicitly convertible to
  261. cstrings <manual.html#types-cstring-type>`_ which makes interaction usually
  262. painless. Most C functions accepting a Nim string converted to a
  263. ``cstring`` will likely not need to keep this string around and by the time
  264. they return the string won't be needed any more. However, for the rare cases
  265. where a Nim string has to be preserved and made available to the C backend
  266. as a ``cstring``, you will need to manually prevent the string data from being
  267. freed with `GC_ref <system.html#GC_ref,string>`_ and `GC_unref
  268. <system.html#GC_unref,string>`_.
  269. A similar thing happens with C code invoking Nim code which returns a
  270. ``cstring``. Consider the following proc:
  271. .. code-block:: nim
  272. proc gimme(): cstring {.exportc.} =
  273. result = "Hey there C code! " & $random(100)
  274. Since Nim's garbage collector is not aware of the C code, once the
  275. ``gimme`` proc has finished it can reclaim the memory of the ``cstring``.
  276. However, from a practical standpoint, the C code invoking the ``gimme``
  277. function directly will be able to use it since Nim's garbage collector has
  278. not had a chance to run *yet*. This gives you enough time to make a copy for
  279. the C side of the program, as calling any further Nim procs *might* trigger
  280. garbage collection making the previously returned string garbage. Or maybe you
  281. are `yourself triggering the collection <gc.html>`_.
  282. Custom data types
  283. -----------------
  284. Just like strings, custom data types that are to be shared between Nim and
  285. the backend will need careful consideration of who controls who. If you want
  286. to hand a Nim reference to C code, you will need to use `GC_ref
  287. <system.html#GC_ref,ref.T>`_ to mark the reference as used, so it does not get
  288. freed. And for the C backend you will need to expose the `GC_unref
  289. <system.html#GC_unref,ref.T>`_ proc to clean up this memory when it is not
  290. required any more.
  291. Again, if you are wrapping a library which *mallocs* and *frees* data
  292. structures, you need to expose the appropriate *free* function to Nim so
  293. you can clean it up. And of course, once cleaned you should avoid accessing it
  294. from Nim (or C for that matter). Typically C data structures have their own
  295. ``malloc_structure`` and ``free_structure`` specific functions, so wrapping
  296. these for the Nim side should be enough.
  297. Thread coordination
  298. -------------------
  299. When the ``NimMain()`` function is called Nim initializes the garbage
  300. collector to the current thread, which is usually the main thread of your
  301. application. If your C code later spawns a different thread and calls Nim
  302. code, the garbage collector will fail to work properly and you will crash.
  303. As long as you don't use the threadvar emulation Nim uses native thread
  304. variables, of which you get a fresh version whenever you create a thread. You
  305. can then attach a GC to this thread via
  306. .. code-block:: nim
  307. system.setupForeignThreadGc()
  308. It is **not** safe to disable the garbage collector and enable it after the
  309. call from your background thread even if the code you are calling is short
  310. lived.
  311. Before the thread exits, you should tear down the thread's GC to prevent memory
  312. leaks by calling
  313. .. code-block:: nim
  314. system.tearDownForeignThreadGc()