nimc.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. List of hints
  50. -------------
  51. Each hint can be activated individually with ``--hint[NAME]:on|off`` or in a
  52. ``push`` pragma.
  53. ========================== ============================================
  54. Name Description
  55. ========================== ============================================
  56. CC Shows when the C compiler is called.
  57. CodeBegin
  58. CodeEnd
  59. CondTrue
  60. Conf A config file was loaded.
  61. ConvToBaseNotNeeded
  62. ConvFromXtoItselfNotNeeded
  63. Dependency
  64. Exec Program is executed.
  65. ExprAlwaysX
  66. ExtendedContext
  67. GCStats Dumps statistics about the Garbage Collector.
  68. GlobalVar Shows global variables declarations.
  69. LineTooLong Line exceeds the maximum length.
  70. Link Linking phase.
  71. Name
  72. Path Search paths modifications.
  73. Pattern
  74. Performance
  75. Processing Artifact being compiled.
  76. QuitCalled
  77. Source The source line that triggered a diagnostic
  78. message.
  79. StackTrace
  80. Success, SuccessX Successful compilation of a library or a binary.
  81. User
  82. UserRaw
  83. XDeclaredButNotUsed Unused symbols in the code.
  84. ========================== ============================================
  85. Verbosity levels
  86. ----------------
  87. ===== ============================================
  88. Level Description
  89. ===== ============================================
  90. 0 Minimal output level for the compiler.
  91. 1 Displays compilation of all the compiled files, including those imported
  92. by other modules or through the `compile pragma<#compile-pragma>`_.
  93. This is the default level.
  94. 2 Displays compilation statistics, enumerates the dynamic
  95. libraries that will be loaded by the final binary and dumps to
  96. standard output the result of applying `a filter to the source code
  97. <filters.html>`_ if any filter was used during compilation.
  98. 3 In addition to the previous levels dumps a debug stack trace
  99. for compiler developers.
  100. ===== ============================================
  101. Compile time symbols
  102. --------------------
  103. Through the ``-d:x`` or ``--define:x`` switch you can define compile time
  104. symbols for conditional compilation. The defined switches can be checked in
  105. source code with the `when statement <manual.html#when-statement>`_ and
  106. `defined proc <system.html#defined>`_. The typical use of this switch is to
  107. enable builds in release mode (``-d:release``) where certain safety checks are
  108. omitted for better performance. Another common use is the ``-d:ssl`` switch to
  109. activate SSL sockets.
  110. Additionally, you may pass a value along with the symbol: ``-d:x=y``
  111. which may be used in conjunction with the `compile time define
  112. pragmas<manual.html#implementation-specific-pragmas-compile-time-define-pragmas>`_
  113. to override symbols during build time.
  114. Compile time symbols are completely **case insensitive** and underscores are
  115. ignored too. ``--define:FOO`` and ``--define:foo`` are identical.
  116. Configuration files
  117. -------------------
  118. **Note:** The *project file name* is the name of the ``.nim`` file that is
  119. passed as a command line argument to the compiler.
  120. The ``nim`` executable processes configuration files in the following
  121. directories (in this order; later files overwrite previous settings):
  122. 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.
  123. 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.
  124. 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.
  125. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option.
  126. 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.
  127. Command line settings have priority over configuration file settings.
  128. The default build of a project is a `debug build`:idx:. To compile a
  129. `release build`:idx: define the ``release`` symbol::
  130. nim c -d:release 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 OSX using the MinGW-w64 toolchain::
  194. nim c -d:mingw myproject.nim
  195. Use ``--cpu:i386`` or ``--cpu:amd64`` to switch the cpu arch.
  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 off runtime checks and turns on the optimizer.
  251. ``useWinAnsi`` Modules like ``os`` and ``osproc`` use the Ansi versions
  252. of the Windows API. The default build uses the Unicode
  253. version.
  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, ableit prefixing each allocation with
  258. its size to support clearing memory on reallocation.
  259. This only works with ``gc:none``.
  260. ``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime
  261. systems. See the documentation of the `gc <gc.html>`_
  262. for further information.
  263. ``nodejs`` The JS target is actually ``node.js``.
  264. ``ssl`` Enables OpenSSL support for the sockets module.
  265. ``memProfiler`` Enables memory profiling for the native GC.
  266. ``uClibc`` Use uClibc instead of libc. (Relevant for Unix-like OSes)
  267. ``checkAbi`` When using types from C headers, add checks that compare
  268. what's in the Nim file with what's in the C header
  269. (requires a C compiler with _Static_assert support, like
  270. any C11 compiler)
  271. ``tempDir`` This symbol takes a string as its value, like
  272. ``--define:tempDir:/some/temp/path`` to override the
  273. temporary directory returned by ``os.getTempDir()``.
  274. The value **should** end with a directory separator
  275. character. (Relevant for the Android platform)
  276. ``useShPath`` This symbol takes a string as its value, like
  277. ``--define:useShPath:/opt/sh/bin/sh`` to override the
  278. path for the ``sh`` binary, in cases where it is not
  279. located in the default location ``/bin/sh``.
  280. ``noSignalHandler`` Disable the crash handler from ``system.nim``.
  281. ====================== =========================================================
  282. Additional Features
  283. ===================
  284. This section describes Nim's additional features that are not listed in the
  285. Nim manual. Some of the features here only make sense for the C code
  286. generator and are subject to change.
  287. LineDir option
  288. --------------
  289. The ``lineDir`` option can be turned on or off. If turned on the
  290. generated C code contains ``#line`` directives. This may be helpful for
  291. debugging with GDB.
  292. StackTrace option
  293. -----------------
  294. If the ``stackTrace`` option is turned on, the generated C contains code to
  295. ensure that proper stack traces are given if the program crashes or an
  296. uncaught exception is raised.
  297. LineTrace option
  298. ----------------
  299. The ``lineTrace`` option implies the ``stackTrace`` option. If turned on,
  300. the generated C contains code to ensure that proper stack traces with line
  301. number information are given if the program crashes or an uncaught exception
  302. is raised.
  303. Hot code reloading
  304. ------------------
  305. **Note:** At the moment hot code reloading is supported only in
  306. JavaScript projects.
  307. The `hotCodeReloading`:idx: option enables special compilation mode where changes in
  308. the code can be applied automatically to a running program. The code reloading
  309. happens at the granularity of an individual module. When a module is reloaded,
  310. Nim will preserve the state of all global variables which are initialized with
  311. a standard variable declaration in the code. All other top level code will be
  312. executed repeatedly on each reload. If you want to prevent this behavior, you
  313. can guard a block of code with the ``once`` construct:
  314. .. code-block:: Nim
  315. var settings = initTable[string, string]()
  316. once:
  317. myInit()
  318. for k, v in loadSettings():
  319. settings[k] = v
  320. If you want to reset the state of a global variable on each reload, just
  321. re-assign a value anywhere within the top-level code:
  322. .. code-block:: Nim
  323. var lastReload: Time
  324. lastReload = now()
  325. resetProgramState()
  326. **Known limitations:** In the JavaScript target, global variables using the
  327. ``codegenDecl`` pragma will be re-initialized on each reload. Please guard the
  328. initialization with a `once` block to work-around this.
  329. **Usage in JavaScript projects:**
  330. Once your code is compiled for hot reloading, you can use a framework such
  331. as `LiveReload <http://livereload.com/>` or `BrowserSync <https://browsersync.io/>`
  332. to implement the actual reloading behavior in your project.
  333. DynlibOverride
  334. ==============
  335. By default Nim's ``dynlib`` pragma causes the compiler to generate
  336. ``GetProcAddress`` (or their Unix counterparts)
  337. calls to bind to a DLL. With the ``dynlibOverride`` command line switch this
  338. can be prevented and then via ``--passL`` the static library can be linked
  339. against. For instance, to link statically against Lua this command might work
  340. on Linux::
  341. nim c --dynlibOverride:lua --passL:liblua.lib program.nim
  342. Backend language options
  343. ========================
  344. The typical compiler usage involves using the ``compile`` or ``c`` command to
  345. transform a ``.nim`` file into one or more ``.c`` files which are then
  346. compiled with the platform's C compiler into a static binary. However there
  347. are other commands to compile to C++, Objective-C or Javascript. More details
  348. can be read in the `Nim Backend Integration document <backends.html>`_.
  349. Nim documentation tools
  350. =======================
  351. Nim provides the `doc`:idx: and `doc2`:idx: commands to generate HTML
  352. documentation from ``.nim`` source files. Only exported symbols will appear in
  353. the output. For more details `see the docgen documentation <docgen.html>`_.
  354. Nim idetools integration
  355. ========================
  356. Nim provides language integration with external IDEs through the
  357. idetools command. See the documentation of `idetools <idetools.html>`_
  358. for further information.
  359. ..
  360. Nim interactive mode
  361. ====================
  362. The Nim compiler supports an interactive mode. This is also known as
  363. a `REPL`:idx: (*read eval print loop*). If Nim has been built with the
  364. ``-d:useGnuReadline`` switch, it uses the GNU readline library for terminal
  365. input management. To start Nim in interactive mode use the command
  366. ``nim secret``. To quit use the ``quit()`` command. To determine whether an input
  367. line is an incomplete statement to be continued these rules are used:
  368. 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace).
  369. 2. The line starts with a space (indentation).
  370. 3. The line is within a triple quoted string literal. However, the detection
  371. does not work if the line contains more than one ``"""``.
  372. Nim for embedded systems
  373. ========================
  374. The standard library can be avoided to a point where C code generation
  375. for 16bit micro controllers is feasible. Use the `standalone`:idx: target
  376. (``--os:standalone``) for a bare bones standard library that lacks any
  377. OS features.
  378. To make the compiler output code for a 16bit target use the ``--cpu:avr``
  379. target.
  380. For example, to generate code for an `AVR`:idx: processor use this command::
  381. nim c --cpu:avr --os:standalone --genScript x.nim
  382. For the ``standalone`` target one needs to provide
  383. a file ``panicoverride.nim``.
  384. See ``tests/manyloc/standalone/panicoverride.nim`` for an example
  385. implementation. Additionally, users should specify the
  386. amount of heap space to use with the ``-d:StandaloneHeapSize=<size>``
  387. command line switch. Note that the total heap size will be
  388. ``<size> * sizeof(float64)``.
  389. Nim for realtime systems
  390. ========================
  391. See the documentation of Nim's soft realtime `GC <gc.html>`_ for further
  392. information.
  393. Signal handling in Nim
  394. ======================
  395. The Nim programming language has no concept of Posix's signal handling
  396. mechanisms. However, the standard library offers some rudimentary support
  397. for signal handling, in particular, segmentation faults are turned into
  398. fatal errors that produce a stack trace. This can be disabled with the
  399. ``-d:noSignalHandler`` switch.
  400. Optimizing for Nim
  401. ==================
  402. Nim has no separate optimizer, but the C code that is produced is very
  403. efficient. Most C compilers have excellent optimizers, so usually it is
  404. not needed to optimize one's code. Nim has been designed to encourage
  405. efficient code: The most readable code in Nim is often the most efficient
  406. too.
  407. However, sometimes one has to optimize. Do it in the following order:
  408. 1. switch off the embedded debugger (it is **slow**!)
  409. 2. turn on the optimizer and turn off runtime checks
  410. 3. profile your code to find where the bottlenecks are
  411. 4. try to find a better algorithm
  412. 5. do low-level optimizations
  413. This section can only help you with the last item.
  414. Optimizing string handling
  415. --------------------------
  416. String assignments are sometimes expensive in Nim: They are required to
  417. copy the whole string. However, the compiler is often smart enough to not copy
  418. strings. Due to the argument passing semantics, strings are never copied when
  419. passed to subroutines. The compiler does not copy strings that are a result from
  420. a procedure call, because the callee returns a new string anyway.
  421. Thus it is efficient to do:
  422. .. code-block:: Nim
  423. var s = procA() # assignment will not copy the string; procA allocates a new
  424. # string already
  425. However it is not efficient to do:
  426. .. code-block:: Nim
  427. var s = varA # assignment has to copy the whole string into a new buffer!
  428. For ``let`` symbols a copy is not always necessary:
  429. .. code-block:: Nim
  430. let s = varA # may only copy a pointer if it safe to do so
  431. If you know what you're doing, you can also mark single string (or sequence)
  432. objects as `shallow`:idx:\:
  433. .. code-block:: Nim
  434. var s = "abc"
  435. shallow(s) # mark 's' as shallow string
  436. var x = s # now might not copy the string!
  437. Usage of ``shallow`` is always safe once you know the string won't be modified
  438. anymore, similar to Ruby's `freeze`:idx:.
  439. The compiler optimizes string case statements: A hashing scheme is used for them
  440. if several different string constants are used. So code like this is reasonably
  441. efficient:
  442. .. code-block:: Nim
  443. case normalize(k.key)
  444. of "name": c.name = v
  445. of "displayname": c.displayName = v
  446. of "version": c.version = v
  447. of "os": c.oses = split(v, {';'})
  448. of "cpu": c.cpus = split(v, {';'})
  449. of "authors": c.authors = split(v, {';'})
  450. of "description": c.description = v
  451. of "app":
  452. case normalize(v)
  453. of "console": c.app = appConsole
  454. of "gui": c.app = appGUI
  455. else: quit(errorStr(p, "expected: console or gui"))
  456. of "license": c.license = UnixToNativePath(k.value)
  457. else: quit(errorStr(p, "unknown variable: " & k.key))