nimc.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. ===================================
  2. Nim Compiler User Guide
  3. ===================================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. contents::
  7. "Look at you, hacker. A pathetic creature of meat and bone, panting and
  8. sweating as you run through my corridors. How can you challenge a perfect,
  9. immortal machine?"
  10. Introduction
  11. ============
  12. This document describes the usage of the *Nim compiler*
  13. on the different supported platforms. It is not a definition of the Nim
  14. programming language (therefore is the `manual <manual.html>`_).
  15. Nim is free software; it is licensed under the
  16. `MIT License <http://www.opensource.org/licenses/mit-license.php>`_.
  17. Compiler Usage
  18. ==============
  19. Command line switches
  20. ---------------------
  21. Basic command line switches are:
  22. Usage:
  23. .. include:: basicopt.txt
  24. ----
  25. Advanced command line switches are:
  26. .. include:: advopt.txt
  27. List of warnings
  28. ----------------
  29. Each warning can be activated individually with ``--warning[NAME]:on|off`` or
  30. in a ``push`` pragma.
  31. ========================== ============================================
  32. Name Description
  33. ========================== ============================================
  34. CannotOpenFile Some file not essential for the compiler's
  35. working could not be opened.
  36. OctalEscape The code contains an unsupported octal
  37. sequence.
  38. Deprecated The code uses a deprecated symbol.
  39. ConfigDeprecated The project makes use of a deprecated config
  40. file.
  41. SmallLshouldNotBeUsed The letter 'l' should not be used as an
  42. identifier.
  43. EachIdentIsTuple The code contains a confusing ``var``
  44. declaration.
  45. ShadowIdent A local variable shadows another local
  46. variable of an outer scope.
  47. User Some user defined warning.
  48. ========================== ============================================
  49. Verbosity levels
  50. ----------------
  51. ===== ============================================
  52. Level Description
  53. ===== ============================================
  54. 0 Minimal output level for the compiler.
  55. 1 Displays compilation of all the compiled files, including those imported
  56. by other modules or through the `compile pragma<#compile-pragma>`_.
  57. This is the default level.
  58. 2 Displays compilation statistics, enumerates the dynamic
  59. libraries that will be loaded by the final binary and dumps to
  60. standard output the result of applying `a filter to the source code
  61. <filters.html>`_ if any filter was used during compilation.
  62. 3 In addition to the previous levels dumps a debug stack trace
  63. for compiler developers.
  64. ===== ============================================
  65. Compile time symbols
  66. --------------------
  67. Through the ``-d:x`` or ``--define:x`` switch you can define compile time
  68. symbols for conditional compilation. The defined switches can be checked in
  69. source code with the `when statement <manual.html#when-statement>`_ and
  70. `defined proc <system.html#defined>`_. The typical use of this switch is to
  71. enable builds in release mode (``-d:release``) where certain safety checks are
  72. omitted for better performance. Another common use is the ``-d:ssl`` switch to
  73. activate `SSL sockets <sockets.html>`_.
  74. Additionally, you may pass a value along with the symbol: ``-d:x=y``
  75. which may be used in conjunction with the `compile time define
  76. pragmas<manual.html#implementation-specific-pragmas-compile-time-define-pragmas>`_
  77. to override symbols during build time.
  78. Configuration files
  79. -------------------
  80. **Note:** The *project file name* is the name of the ``.nim`` file that is
  81. passed as a command line argument to the compiler.
  82. The ``nim`` executable processes configuration files in the following
  83. directories (in this order; later files overwrite previous settings):
  84. 1) ``$nim/config/nim.cfg``, ``/etc/nim.cfg`` (UNIX) or ``%NIMROD%/config/nim.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option.
  85. 2) ``/home/$user/.config/nim.cfg`` (UNIX) or ``%APPDATA%/nim.cfg`` (Windows). This file can be skipped with the ``--skipUserCfg`` command line option.
  86. 3) ``$parentDir/nim.cfg`` where ``$parentDir`` stands for any parent directory of the project file's path. These files can be skipped with the ``--skipParentCfg`` command line option.
  87. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option.
  88. 5) A project can also have a project specific configuration file named ``$project.nim.cfg`` that resides in the same directory as ``$project.nim``. This file can be skipped with the ``--skipProjCfg`` command line option.
  89. Command line settings have priority over configuration file settings.
  90. The default build of a project is a `debug build`:idx:. To compile a
  91. `release build`:idx: define the ``release`` symbol::
  92. nim c -d:release myproject.nim
  93. Search path handling
  94. --------------------
  95. Nim has the concept of a global search path (PATH) that is queried to
  96. determine where to find imported modules or include files. If multiple files are
  97. found an ambiguity error is produced.
  98. ``nim dump`` shows the contents of the PATH.
  99. However before the PATH is used the current directory is checked for the
  100. file's existence. So if PATH contains ``$lib`` and ``$lib/bar`` and the
  101. directory structure looks like this::
  102. $lib/x.nim
  103. $lib/bar/x.nim
  104. foo/x.nim
  105. foo/main.nim
  106. other.nim
  107. And ``main`` imports ``x``, ``foo/x`` is imported. If ``other`` imports ``x``
  108. then both ``$lib/x.nim`` and ``$lib/bar/x.nim`` match and so the compiler
  109. should reject it. Currently however this check is not implemented and instead
  110. the first matching file is used.
  111. Generated C code directory
  112. --------------------------
  113. The generated files that Nim produces all go into a subdirectory called
  114. ``nimcache`` in your project directory. This makes it easy to delete all
  115. generated files. Files generated in this directory follow a naming logic which
  116. you can read about in the `Nim Backend Integration document
  117. <backends.html#nimcache-naming-logic>`_.
  118. However, the generated C code is not platform independent. C code generated for
  119. Linux does not compile on Windows, for instance. The comment on top of the
  120. C file lists the OS, CPU and CC the file has been compiled for.
  121. Compilation cache
  122. =================
  123. **Warning**: The compilation cache is still highly experimental!
  124. The ``nimcache`` directory may also contain so called `rod`:idx:
  125. or `symbol files`:idx:. These files are pre-compiled modules that are used by
  126. the compiler to perform `incremental compilation`:idx:. This means that only
  127. modules that have changed since the last compilation (or the modules depending
  128. on them etc.) are re-compiled. However, per default no symbol files are
  129. generated; use the ``--symbolFiles:on`` command line switch to activate them.
  130. Unfortunately due to technical reasons the ``--symbolFiles:on`` needs
  131. to *aggregate* some generated C code. This means that the resulting executable
  132. might contain some cruft even when dead code elimination is turned on. So
  133. the final release build should be done with ``--symbolFiles:off``.
  134. Due to the aggregation of C code it is also recommended that each project
  135. resides in its own directory so that the generated ``nimcache`` directory
  136. is not shared between different projects.
  137. Compiler Selection
  138. ==================
  139. To change the compiler from the default compiler (at the command line)::
  140. nim c --cc:llvm_gcc --compile_only myfile.nim
  141. This uses the configuration defined in ``config\nim.cfg`` for ``lvm_gcc``.
  142. If nimcache already contains compiled code from a different compiler for the same project,
  143. add the ``-f`` flag to force all files to be recompiled.
  144. The default compiler is defined at the top of ``config\nim.cfg``. Changing this setting
  145. affects the compiler used by ``koch`` to (re)build Nim.
  146. Cross compilation
  147. =================
  148. To cross compile, use for example::
  149. nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim
  150. Then move the C code and the compile script ``compile_myproject.sh`` to your
  151. Linux i386 machine and run the script.
  152. Another way is to make Nim invoke a cross compiler toolchain::
  153. nim c --cpu:arm --os:linux myproject.nim
  154. For cross compilation, the compiler invokes a C compiler named
  155. like ``$cpu.$os.$cc`` (for example arm.linux.gcc) and the configuration
  156. system is used to provide meaningful defaults. For example for ``ARM`` your
  157. configuration file should contain something like::
  158. arm.linux.gcc.path = "/usr/bin"
  159. arm.linux.gcc.exe = "arm-linux-gcc"
  160. arm.linux.gcc.linkerexe = "arm-linux-gcc"
  161. DLL generation
  162. ==============
  163. Nim supports the generation of DLLs. However, there must be only one
  164. instance of the GC per process/address space. This instance is contained in
  165. ``nimrtl.dll``. This means that every generated Nim DLL depends
  166. on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command::
  167. nim c -d:release lib/nimrtl.nim
  168. To link against ``nimrtl.dll`` use the command::
  169. nim c -d:useNimRtl myprog.nim
  170. **Note**: Currently the creation of ``nimrtl.dll`` with thread support has
  171. never been tested and is unlikely to work!
  172. Additional compilation switches
  173. ===============================
  174. The standard library supports a growing number of ``useX`` conditional defines
  175. affecting how some features are implemented. This section tries to give a
  176. complete list.
  177. ================== =========================================================
  178. Define Effect
  179. ================== =========================================================
  180. ``release`` Turns off runtime checks and turns on the optimizer.
  181. ``useWinAnsi`` Modules like ``os`` and ``osproc`` use the Ansi versions
  182. of the Windows API. The default build uses the Unicode
  183. version.
  184. ``useFork`` Makes ``osproc`` use ``fork`` instead of ``posix_spawn``.
  185. ``useNimRtl`` Compile and link against ``nimrtl.dll``.
  186. ``useMalloc`` Makes Nim use C's `malloc`:idx: instead of Nim's
  187. own memory manager, ableit prefixing each allocation with
  188. its size to support clearing memory on reallocation.
  189. This only works with ``gc:none``.
  190. ``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime
  191. systems. See the documentation of the `gc <gc.html>`_
  192. for further information.
  193. ``nodejs`` The JS target is actually ``node.js``.
  194. ``ssl`` Enables OpenSSL support for the sockets module.
  195. ``memProfiler`` Enables memory profiling for the native GC.
  196. ``uClibc`` Use uClibc instead of libc. (Relevant for Unix-like OSes)
  197. ``checkAbi`` When using types from C headers, add checks that compare
  198. what's in the Nim file with what's in the C header
  199. (requires a C compiler with _Static_assert support, like
  200. any C11 compiler)
  201. ``tempDir`` This symbol takes a string as its value, like
  202. ``--define:tempDir:/some/temp/path`` to override the
  203. temporary directory returned by ``os.getTempDir()``.
  204. The value **should** end with a directory separator
  205. character. (Relevant for the Android platform)
  206. ``useShPath`` This symbol takes a string as its value, like
  207. ``--define:useShPath:/opt/sh/bin/sh`` to override the
  208. path for the ``sh`` binary, in cases where it is not
  209. located in the default location ``/bin/sh``
  210. ================== =========================================================
  211. Additional Features
  212. ===================
  213. This section describes Nim's additional features that are not listed in the
  214. Nim manual. Some of the features here only make sense for the C code
  215. generator and are subject to change.
  216. LineDir option
  217. --------------
  218. The ``lineDir`` option can be turned on or off. If turned on the
  219. generated C code contains ``#line`` directives. This may be helpful for
  220. debugging with GDB.
  221. StackTrace option
  222. -----------------
  223. If the ``stackTrace`` option is turned on, the generated C contains code to
  224. ensure that proper stack traces are given if the program crashes or an
  225. uncaught exception is raised.
  226. LineTrace option
  227. ----------------
  228. The ``lineTrace`` option implies the ``stackTrace`` option. If turned on,
  229. the generated C contains code to ensure that proper stack traces with line
  230. number information are given if the program crashes or an uncaught exception
  231. is raised.
  232. Debugger option
  233. ---------------
  234. The ``debugger`` option enables or disables the *Embedded Nim Debugger*.
  235. See the documentation of endb_ for further information.
  236. Breakpoint pragma
  237. -----------------
  238. The *breakpoint* pragma was specially added for the sake of debugging with
  239. ENDB. See the documentation of `endb <endb.html>`_ for further information.
  240. DynlibOverride
  241. ==============
  242. By default Nim's ``dynlib`` pragma causes the compiler to generate
  243. ``GetProcAddress`` (or their Unix counterparts)
  244. calls to bind to a DLL. With the ``dynlibOverride`` command line switch this
  245. can be prevented and then via ``--passL`` the static library can be linked
  246. against. For instance, to link statically against Lua this command might work
  247. on Linux::
  248. nim c --dynlibOverride:lua --passL:liblua.lib program.nim
  249. Backend language options
  250. ========================
  251. The typical compiler usage involves using the ``compile`` or ``c`` command to
  252. transform a ``.nim`` file into one or more ``.c`` files which are then
  253. compiled with the platform's C compiler into a static binary. However there
  254. are other commands to compile to C++, Objective-C or Javascript. More details
  255. can be read in the `Nim Backend Integration document <backends.html>`_.
  256. Nim documentation tools
  257. =======================
  258. Nim provides the `doc`:idx: and `doc2`:idx: commands to generate HTML
  259. documentation from ``.nim`` source files. Only exported symbols will appear in
  260. the output. For more details `see the docgen documentation <docgen.html>`_.
  261. Nim idetools integration
  262. ========================
  263. Nim provides language integration with external IDEs through the
  264. idetools command. See the documentation of `idetools <idetools.html>`_
  265. for further information.
  266. ..
  267. Nim interactive mode
  268. ====================
  269. The Nim compiler supports an interactive mode. This is also known as
  270. a `REPL`:idx: (*read eval print loop*). If Nim has been built with the
  271. ``-d:useGnuReadline`` switch, it uses the GNU readline library for terminal
  272. input management. To start Nim in interactive mode use the command
  273. ``nim secret``. To quit use the ``quit()`` command. To determine whether an input
  274. line is an incomplete statement to be continued these rules are used:
  275. 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace).
  276. 2. The line starts with a space (indentation).
  277. 3. The line is within a triple quoted string literal. However, the detection
  278. does not work if the line contains more than one ``"""``.
  279. Nim for embedded systems
  280. ========================
  281. The standard library can be avoided to a point where C code generation
  282. for 16bit micro controllers is feasible. Use the `standalone`:idx: target
  283. (``--os:standalone``) for a bare bones standard library that lacks any
  284. OS features.
  285. To make the compiler output code for a 16bit target use the ``--cpu:avr``
  286. target.
  287. For example, to generate code for an `AVR`:idx: processor use this command::
  288. nim c --cpu:avr --os:standalone --deadCodeElim:on --genScript x.nim
  289. For the ``standalone`` target one needs to provide
  290. a file ``panicoverride.nim``.
  291. See ``tests/manyloc/standalone/panicoverride.nim`` for an example
  292. implementation. Additionally, users should specify the
  293. amount of heap space to use with the ``-d:StandaloneHeapSize=<size>``
  294. command line switch. Note that the total heap size will be
  295. ``<size> * sizeof(float64)``.
  296. Nim for realtime systems
  297. ========================
  298. See the documentation of Nim's soft realtime `GC <gc.html>`_ for further
  299. information.
  300. Debugging with Nim
  301. ==================
  302. Nim comes with its own *Embedded Nim Debugger*. See
  303. the documentation of endb_ for further information.
  304. Optimizing for Nim
  305. ==================
  306. Nim has no separate optimizer, but the C code that is produced is very
  307. efficient. Most C compilers have excellent optimizers, so usually it is
  308. not needed to optimize one's code. Nim has been designed to encourage
  309. efficient code: The most readable code in Nim is often the most efficient
  310. too.
  311. However, sometimes one has to optimize. Do it in the following order:
  312. 1. switch off the embedded debugger (it is **slow**!)
  313. 2. turn on the optimizer and turn off runtime checks
  314. 3. profile your code to find where the bottlenecks are
  315. 4. try to find a better algorithm
  316. 5. do low-level optimizations
  317. This section can only help you with the last item.
  318. Optimizing string handling
  319. --------------------------
  320. String assignments are sometimes expensive in Nim: They are required to
  321. copy the whole string. However, the compiler is often smart enough to not copy
  322. strings. Due to the argument passing semantics, strings are never copied when
  323. passed to subroutines. The compiler does not copy strings that are a result from
  324. a procedure call, because the callee returns a new string anyway.
  325. Thus it is efficient to do:
  326. .. code-block:: Nim
  327. var s = procA() # assignment will not copy the string; procA allocates a new
  328. # string already
  329. However it is not efficient to do:
  330. .. code-block:: Nim
  331. var s = varA # assignment has to copy the whole string into a new buffer!
  332. For ``let`` symbols a copy is not always necessary:
  333. .. code-block:: Nim
  334. let s = varA # may only copy a pointer if it safe to do so
  335. If you know what you're doing, you can also mark single string (or sequence)
  336. objects as `shallow`:idx:\:
  337. .. code-block:: Nim
  338. var s = "abc"
  339. shallow(s) # mark 's' as shallow string
  340. var x = s # now might not copy the string!
  341. Usage of ``shallow`` is always safe once you know the string won't be modified
  342. anymore, similar to Ruby's `freeze`:idx:.
  343. The compiler optimizes string case statements: A hashing scheme is used for them
  344. if several different string constants are used. So code like this is reasonably
  345. efficient:
  346. .. code-block:: Nim
  347. case normalize(k.key)
  348. of "name": c.name = v
  349. of "displayname": c.displayName = v
  350. of "version": c.version = v
  351. of "os": c.oses = split(v, {';'})
  352. of "cpu": c.cpus = split(v, {';'})
  353. of "authors": c.authors = split(v, {';'})
  354. of "description": c.description = v
  355. of "app":
  356. case normalize(v)
  357. of "console": c.app = appConsole
  358. of "gui": c.app = appGUI
  359. else: quit(errorStr(p, "expected: console or gui"))
  360. of "license": c.license = UnixToNativePath(k.value)
  361. else: quit(errorStr(p, "unknown variable: " & k.key))