backends.rst 16 KB

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