backends.rst 16 KB

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