nimc.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. User Some user defined warning.
  46. ========================== ============================================
  47. List of hints
  48. -------------
  49. Each hint can be activated individually with ``--hint[NAME]:on|off`` or in a
  50. ``push`` pragma.
  51. ========================== ============================================
  52. Name Description
  53. ========================== ============================================
  54. CC Shows when the C compiler is called.
  55. CodeBegin
  56. CodeEnd
  57. CondTrue
  58. Conf A config file was loaded.
  59. ConvToBaseNotNeeded
  60. ConvFromXtoItselfNotNeeded
  61. Dependency
  62. Exec Program is executed.
  63. ExprAlwaysX
  64. ExtendedContext
  65. GCStats Dumps statistics about the Garbage Collector.
  66. GlobalVar Shows global variables declarations.
  67. LineTooLong Line exceeds the maximum length.
  68. Link Linking phase.
  69. Name
  70. Path Search paths modifications.
  71. Pattern
  72. Performance
  73. Processing Artifact being compiled.
  74. QuitCalled
  75. Source The source line that triggered a diagnostic
  76. message.
  77. StackTrace
  78. Success, SuccessX Successful compilation of a library or a binary.
  79. User
  80. UserRaw
  81. XDeclaredButNotUsed Unused symbols in the code.
  82. ========================== ============================================
  83. Verbosity levels
  84. ----------------
  85. ===== ============================================
  86. Level Description
  87. ===== ============================================
  88. 0 Minimal output level for the compiler.
  89. 1 Displays compilation of all the compiled files, including those imported
  90. by other modules or through the `compile pragma<#compile-pragma>`_.
  91. This is the default level.
  92. 2 Displays compilation statistics, enumerates the dynamic
  93. libraries that will be loaded by the final binary and dumps to
  94. standard output the result of applying `a filter to the source code
  95. <filters.html>`_ if any filter was used during compilation.
  96. 3 In addition to the previous levels dumps a debug stack trace
  97. for compiler developers.
  98. ===== ============================================
  99. Compile time symbols
  100. --------------------
  101. Through the ``-d:x`` or ``--define:x`` switch you can define compile time
  102. symbols for conditional compilation. The defined switches can be checked in
  103. source code with the `when statement <manual.html#when-statement>`_ and
  104. `defined proc <system.html#defined>`_. The typical use of this switch is to
  105. enable builds in release mode (``-d:release``) where optimizations are
  106. enabled for better performance. Another common use is the ``-d:ssl`` switch to
  107. activate SSL sockets.
  108. Additionally, you may pass a value along with the symbol: ``-d:x=y``
  109. which may be used in conjunction with the `compile time define
  110. pragmas<manual.html#implementation-specific-pragmas-compile-time-define-pragmas>`_
  111. to override symbols during build time.
  112. Compile time symbols are completely **case insensitive** and underscores are
  113. ignored too. ``--define:FOO`` and ``--define:foo`` are identical.
  114. Configuration files
  115. -------------------
  116. **Note:** The *project file name* is the name of the ``.nim`` file that is
  117. passed as a command line argument to the compiler.
  118. The ``nim`` executable processes configuration files in the following
  119. directories (in this order; later files overwrite previous settings):
  120. 1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or ``<Nim's installation director>\config\nim.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option.
  121. 2) If environment variable ``XDG_CONFIG_HOME`` is defined, ``$XDG_CONFIG_HOME/nim/nim.cfg`` or ``~/.config/nim/nim.cfg`` (POSIX) or ``%APPDATA%/nim/nim.cfg`` (Windows). This file can be skipped with the ``--skipUserCfg`` command line option.
  122. 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.
  123. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option.
  124. 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.
  125. Command line settings have priority over configuration file settings.
  126. The default build of a project is a `debug build`:idx:. To compile a
  127. `release build`:idx: define the ``release`` symbol::
  128. nim c -d:release myproject.nim
  129. To compile a `dangerous release build`:idx: define the ``danger`` symbol::
  130. nim c -d:danger myproject.nim
  131. Search path handling
  132. --------------------
  133. Nim has the concept of a global search path (PATH) that is queried to
  134. determine where to find imported modules or include files. If multiple files are
  135. found an ambiguity error is produced.
  136. ``nim dump`` shows the contents of the PATH.
  137. However before the PATH is used the current directory is checked for the
  138. file's existence. So if PATH contains ``$lib`` and ``$lib/bar`` and the
  139. directory structure looks like this::
  140. $lib/x.nim
  141. $lib/bar/x.nim
  142. foo/x.nim
  143. foo/main.nim
  144. other.nim
  145. And ``main`` imports ``x``, ``foo/x`` is imported. If ``other`` imports ``x``
  146. then both ``$lib/x.nim`` and ``$lib/bar/x.nim`` match and so the compiler
  147. should reject it. Currently however this check is not implemented and instead
  148. the first matching file is used.
  149. Generated C code directory
  150. --------------------------
  151. The generated files that Nim produces all go into a subdirectory called
  152. ``nimcache``. Its full path is
  153. - ``$XDG_CACHE_HOME/nim/$projectname(_r|_d)`` or ``~/.cache/nim/$projectname(_r|_d)``
  154. on Posix
  155. - ``$HOME/nimcache/$projectname(_r|_d)`` on Windows.
  156. The ``_r`` suffix is used for release builds, ``_d`` is for debug builds.
  157. This makes it easy to delete all
  158. generated files. Files generated in this directory follow a naming logic which
  159. you can read about in the `Nim Backend Integration document
  160. <backends.html#nimcache-naming-logic>`_.
  161. The ``--nimcache``
  162. `compiler switch <nimc.html#command-line-switches>`_ can be used to
  163. to change the ``nimcache`` directory.
  164. However, the generated C code is not platform independent. C code generated for
  165. Linux does not compile on Windows, for instance. The comment on top of the
  166. C file lists the OS, CPU and CC the file has been compiled for.
  167. Compiler Selection
  168. ==================
  169. To change the compiler from the default compiler (at the command line)::
  170. nim c --cc:llvm_gcc --compile_only myfile.nim
  171. This uses the configuration defined in ``config\nim.cfg`` for ``lvm_gcc``.
  172. If nimcache already contains compiled code from a different compiler for the same project,
  173. add the ``-f`` flag to force all files to be recompiled.
  174. The default compiler is defined at the top of ``config\nim.cfg``. Changing this setting
  175. affects the compiler used by ``koch`` to (re)build Nim.
  176. Cross compilation
  177. =================
  178. To cross compile, use for example::
  179. nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim
  180. Then move the C code and the compile script ``compile_myproject.sh`` to your
  181. Linux i386 machine and run the script.
  182. Another way is to make Nim invoke a cross compiler toolchain::
  183. nim c --cpu:arm --os:linux myproject.nim
  184. For cross compilation, the compiler invokes a C compiler named
  185. like ``$cpu.$os.$cc`` (for example arm.linux.gcc) and the configuration
  186. system is used to provide meaningful defaults. For example for ``ARM`` your
  187. configuration file should contain something like::
  188. arm.linux.gcc.path = "/usr/bin"
  189. arm.linux.gcc.exe = "arm-linux-gcc"
  190. arm.linux.gcc.linkerexe = "arm-linux-gcc"
  191. Cross compilation for Windows
  192. =============================
  193. To cross compile for Windows from Linux or macOS using the MinGW-w64 toolchain::
  194. nim c -d:mingw myproject.nim
  195. Use ``--cpu:i386`` or ``--cpu:amd64`` to switch the CPU architecture.
  196. The MinGW-w64 toolchain can be installed as follows::
  197. Ubuntu: apt install mingw-w64
  198. CentOS: yum install mingw32-gcc | mingw64-gcc - requires EPEL
  199. OSX: brew install mingw-w64
  200. Cross compilation for Nintendo Switch
  201. =====================================
  202. Simply add --os:nintendoswitch
  203. to your usual ``nim c`` or ``nim cpp`` command and set the ``passC``
  204. and ``passL`` command line switches to something like:
  205. .. code-block:: console
  206. nim c ... --passC="-I$DEVKITPRO/libnx/include" ...
  207. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  208. or setup a nim.cfg file like so:
  209. .. code-block:: Nim
  210. #nim.cfg
  211. --passC="-I$DEVKITPRO/libnx/include"
  212. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  213. The DevkitPro setup must be the same as the default with their new installer
  214. `here for Mac/Linux <https://github.com/devkitPro/pacman/releases>`_ or
  215. `here for Windows <https://github.com/devkitPro/installer/releases>`_.
  216. For example, with the above mentioned config::
  217. nim c --os:nintendoswitch switchhomebrew.nim
  218. This will generate a file called ``switchhomebrew.elf`` which can then be turned into
  219. an nro file with the ``elf2nro`` tool in the DevkitPro release. Examples can be found at
  220. `the nim-libnx github repo <https://github.com/jyapayne/nim-libnx.git>`_.
  221. There are a few things that don't work because the DevkitPro libraries don't support them.
  222. They are:
  223. 1. Waiting for a subprocess to finish. A subprocess can be started, but right
  224. now it can't be waited on, which sort of makes subprocesses a bit hard to use
  225. 2. Dynamic calls. DevkitPro libraries have no dlopen/dlclose functions.
  226. 3. Command line parameters. It doesn't make sense to have these for a console
  227. anyways, so no big deal here.
  228. 4. mqueue. Sadly there are no mqueue headers.
  229. 5. ucontext. No headers for these either. No coroutines for now :(
  230. 6. nl_types. No headers for this.
  231. DLL generation
  232. ==============
  233. Nim supports the generation of DLLs. However, there must be only one
  234. instance of the GC per process/address space. This instance is contained in
  235. ``nimrtl.dll``. This means that every generated Nim DLL depends
  236. on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command::
  237. nim c -d:release lib/nimrtl.nim
  238. To link against ``nimrtl.dll`` use the command::
  239. nim c -d:useNimRtl myprog.nim
  240. **Note**: Currently the creation of ``nimrtl.dll`` with thread support has
  241. never been tested and is unlikely to work!
  242. Additional compilation switches
  243. ===============================
  244. The standard library supports a growing number of ``useX`` conditional defines
  245. affecting how some features are implemented. This section tries to give a
  246. complete list.
  247. ====================== =========================================================
  248. Define Effect
  249. ====================== =========================================================
  250. ``release`` Turns on the optimizer.
  251. More aggressive optimizations are possible, eg:
  252. ``--passC:-ffast-math`` (but see issue #10305)
  253. ``danger`` Turns off all runtime checks and turns on the optimizer.
  254. ``useFork`` Makes ``osproc`` use ``fork`` instead of ``posix_spawn``.
  255. ``useNimRtl`` Compile and link against ``nimrtl.dll``.
  256. ``useMalloc`` Makes Nim use C's `malloc`:idx: instead of Nim's
  257. own memory manager, albeit prefixing each allocation with
  258. its size to support clearing memory on reallocation.
  259. This only works with ``gc:none`` and
  260. with ``--newruntime``.
  261. ``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime
  262. systems. See the documentation of the `gc <gc.html>`_
  263. for further information.
  264. ``logGC`` Enable GC logging to stdout.
  265. ``nodejs`` The JS target is actually ``node.js``.
  266. ``ssl`` Enables OpenSSL support for the sockets module.
  267. ``memProfiler`` Enables memory profiling for the native GC.
  268. ``uClibc`` Use uClibc instead of libc. (Relevant for Unix-like OSes)
  269. ``checkAbi`` When using types from C headers, add checks that compare
  270. what's in the Nim file with what's in the C header
  271. (requires a C compiler with _Static_assert support, like
  272. any C11 compiler)
  273. ``tempDir`` This symbol takes a string as its value, like
  274. ``--define:tempDir:/some/temp/path`` to override the
  275. temporary directory returned by ``os.getTempDir()``.
  276. The value **should** end with a directory separator
  277. character. (Relevant for the Android platform)
  278. ``useShPath`` This symbol takes a string as its value, like
  279. ``--define:useShPath:/opt/sh/bin/sh`` to override the
  280. path for the ``sh`` binary, in cases where it is not
  281. located in the default location ``/bin/sh``.
  282. ``noSignalHandler`` Disable the crash handler from ``system.nim``.
  283. ====================== =========================================================
  284. Additional Features
  285. ===================
  286. This section describes Nim's additional features that are not listed in the
  287. Nim manual. Some of the features here only make sense for the C code
  288. generator and are subject to change.
  289. LineDir option
  290. --------------
  291. The ``lineDir`` option can be turned on or off. If turned on the
  292. generated C code contains ``#line`` directives. This may be helpful for
  293. debugging with GDB.
  294. StackTrace option
  295. -----------------
  296. If the ``stackTrace`` option is turned on, the generated C contains code to
  297. ensure that proper stack traces are given if the program crashes or an
  298. uncaught exception is raised.
  299. LineTrace option
  300. ----------------
  301. The ``lineTrace`` option implies the ``stackTrace`` option. If turned on,
  302. the generated C contains code to ensure that proper stack traces with line
  303. number information are given if the program crashes or an uncaught exception
  304. is raised.
  305. DynlibOverride
  306. ==============
  307. By default Nim's ``dynlib`` pragma causes the compiler to generate
  308. ``GetProcAddress`` (or their Unix counterparts)
  309. calls to bind to a DLL. With the ``dynlibOverride`` command line switch this
  310. can be prevented and then via ``--passL`` the static library can be linked
  311. against. For instance, to link statically against Lua this command might work
  312. on Linux::
  313. nim c --dynlibOverride:lua --passL:liblua.lib program.nim
  314. Cursor pragma
  315. =============
  316. The ``.cursor`` pragma is a temporary tool for optimization purposes
  317. and this property will be computed by Nim's optimizer eventually. Thus it
  318. remains undocumented.
  319. Backend language options
  320. ========================
  321. The typical compiler usage involves using the ``compile`` or ``c`` command to
  322. transform a ``.nim`` file into one or more ``.c`` files which are then
  323. compiled with the platform's C compiler into a static binary. However there
  324. are other commands to compile to C++, Objective-C or JavaScript. More details
  325. can be read in the `Nim Backend Integration document <backends.html>`_.
  326. Nim documentation tools
  327. =======================
  328. Nim provides the `doc`:idx: and `doc2`:idx: commands to generate HTML
  329. documentation from ``.nim`` source files. Only exported symbols will appear in
  330. the output. For more details `see the docgen documentation <docgen.html>`_.
  331. Nim idetools integration
  332. ========================
  333. Nim provides language integration with external IDEs through the
  334. idetools command. See the documentation of `idetools <idetools.html>`_
  335. for further information.
  336. ..
  337. Nim interactive mode
  338. ====================
  339. The Nim compiler supports an interactive mode. This is also known as
  340. a `REPL`:idx: (*read eval print loop*). If Nim has been built with the
  341. ``-d:useGnuReadline`` switch, it uses the GNU readline library for terminal
  342. input management. To start Nim in interactive mode use the command
  343. ``nim secret``. To quit use the ``quit()`` command. To determine whether an input
  344. line is an incomplete statement to be continued these rules are used:
  345. 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace).
  346. 2. The line starts with a space (indentation).
  347. 3. The line is within a triple quoted string literal. However, the detection
  348. does not work if the line contains more than one ``"""``.
  349. Nim for embedded systems
  350. ========================
  351. The standard library can be avoided to a point where C code generation
  352. for 16bit micro controllers is feasible. Use the `standalone`:idx: target
  353. (``--os:standalone``) for a bare bones standard library that lacks any
  354. OS features.
  355. To make the compiler output code for a 16bit target use the ``--cpu:avr``
  356. target.
  357. For example, to generate code for an `AVR`:idx: processor use this command::
  358. nim c --cpu:avr --os:standalone --genScript x.nim
  359. For the ``standalone`` target one needs to provide
  360. a file ``panicoverride.nim``.
  361. See ``tests/manyloc/standalone/panicoverride.nim`` for an example
  362. implementation. Additionally, users should specify the
  363. amount of heap space to use with the ``-d:StandaloneHeapSize=<size>``
  364. command line switch. Note that the total heap size will be
  365. ``<size> * sizeof(float64)``.
  366. Nim for realtime systems
  367. ========================
  368. See the documentation of Nim's soft realtime `GC <gc.html>`_ for further
  369. information.
  370. Signal handling in Nim
  371. ======================
  372. The Nim programming language has no concept of Posix's signal handling
  373. mechanisms. However, the standard library offers some rudimentary support
  374. for signal handling, in particular, segmentation faults are turned into
  375. fatal errors that produce a stack trace. This can be disabled with the
  376. ``-d:noSignalHandler`` switch.
  377. Optimizing for Nim
  378. ==================
  379. Nim has no separate optimizer, but the C code that is produced is very
  380. efficient. Most C compilers have excellent optimizers, so usually it is
  381. not needed to optimize one's code. Nim has been designed to encourage
  382. efficient code: The most readable code in Nim is often the most efficient
  383. too.
  384. However, sometimes one has to optimize. Do it in the following order:
  385. 1. switch off the embedded debugger (it is **slow**!)
  386. 2. turn on the optimizer and turn off runtime checks
  387. 3. profile your code to find where the bottlenecks are
  388. 4. try to find a better algorithm
  389. 5. do low-level optimizations
  390. This section can only help you with the last item.
  391. Optimizing string handling
  392. --------------------------
  393. String assignments are sometimes expensive in Nim: They are required to
  394. copy the whole string. However, the compiler is often smart enough to not copy
  395. strings. Due to the argument passing semantics, strings are never copied when
  396. passed to subroutines. The compiler does not copy strings that are a result from
  397. a procedure call, because the callee returns a new string anyway.
  398. Thus it is efficient to do:
  399. .. code-block:: Nim
  400. var s = procA() # assignment will not copy the string; procA allocates a new
  401. # string already
  402. However it is not efficient to do:
  403. .. code-block:: Nim
  404. var s = varA # assignment has to copy the whole string into a new buffer!
  405. For ``let`` symbols a copy is not always necessary:
  406. .. code-block:: Nim
  407. let s = varA # may only copy a pointer if it safe to do so
  408. If you know what you're doing, you can also mark single string (or sequence)
  409. objects as `shallow`:idx:\:
  410. .. code-block:: Nim
  411. var s = "abc"
  412. shallow(s) # mark 's' as shallow string
  413. var x = s # now might not copy the string!
  414. Usage of ``shallow`` is always safe once you know the string won't be modified
  415. anymore, similar to Ruby's `freeze`:idx:.
  416. The compiler optimizes string case statements: A hashing scheme is used for them
  417. if several different string constants are used. So code like this is reasonably
  418. efficient:
  419. .. code-block:: Nim
  420. case normalize(k.key)
  421. of "name": c.name = v
  422. of "displayname": c.displayName = v
  423. of "version": c.version = v
  424. of "os": c.oses = split(v, {';'})
  425. of "cpu": c.cpus = split(v, {';'})
  426. of "authors": c.authors = split(v, {';'})
  427. of "description": c.description = v
  428. of "app":
  429. case normalize(v)
  430. of "console": c.app = appConsole
  431. of "gui": c.app = appGUI
  432. else: quit(errorStr(p, "expected: console or gui"))
  433. of "license": c.license = UnixToNativePath(k.value)
  434. else: quit(errorStr(p, "unknown variable: " & k.key))