nimc.rst 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. ===================================
  2. Nim Compiler User Guide
  3. ===================================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. default-role:: code
  7. .. include:: rstcommon.rst
  8. .. contents::
  9. ..
  10. "Look at you, hacker. A pathetic creature of meat and bone, panting and
  11. sweating as you run through my corridors. How can you challenge a perfect,
  12. immortal machine?"
  13. Introduction
  14. ============
  15. This document describes the usage of the *Nim compiler*
  16. on the different supported platforms. It is not a definition of the Nim
  17. programming language (which is covered in the `manual <manual.html>`_).
  18. Nim is free software; it is licensed under the
  19. `MIT License <http://www.opensource.org/licenses/mit-license.php>`_.
  20. Compiler Usage
  21. ==============
  22. Command-line switches
  23. ---------------------
  24. Basic command-line switches are:
  25. .. no syntax highlighting in the below included files at the moment
  26. .. default-role:: code
  27. Usage:
  28. .. include:: basicopt.txt
  29. ----
  30. Advanced command-line switches are:
  31. .. include:: advopt.txt
  32. .. include:: rstcommon.rst
  33. List of warnings
  34. ----------------
  35. Each warning can be activated individually with `--warning:NAME:on|off`:option: or
  36. in a `push` pragma with `{.warning[NAME]:on|off.}`.
  37. ========================== ============================================
  38. Name Description
  39. ========================== ============================================
  40. CannotOpenFile Some file not essential for the compiler's
  41. working could not be opened.
  42. OctalEscape The code contains an unsupported octal
  43. sequence.
  44. Deprecated The code uses a deprecated symbol.
  45. ConfigDeprecated The project makes use of a deprecated config
  46. file.
  47. SmallLshouldNotBeUsed The letter 'l' should not be used as an
  48. identifier.
  49. EachIdentIsTuple The code contains a confusing `var`
  50. declaration.
  51. CStringConv Warn about dangerous implicit conversions
  52. to `cstring`.
  53. EnumConv Warn about conversions from enum to enum.
  54. AnyEnumConv Warn about any conversions to an enum type.
  55. HoleEnumConv Warn about conversion to an enum with
  56. holes. These conversions are unsafe.
  57. ResultUsed Warn about the usage of the
  58. built-in `result` variable.
  59. User Some user-defined warning.
  60. ========================== ============================================
  61. List of hints
  62. -------------
  63. Each hint can be activated individually with `--hint:NAME:on|off`:option: or in a
  64. `push` pragma with `{.hint[NAME]:on|off.}`.
  65. ========================== ============================================
  66. Name Description
  67. ========================== ============================================
  68. CC Shows when the C compiler is called.
  69. CodeBegin
  70. CodeEnd
  71. CondTrue
  72. Conf A config file was loaded.
  73. ConvToBaseNotNeeded
  74. ConvFromXtoItselfNotNeeded
  75. Dependency
  76. Exec Program is executed.
  77. ExprAlwaysX
  78. ExtendedContext
  79. GCStats Dumps statistics about the Garbage Collector.
  80. GlobalVar Shows global variables declarations.
  81. LineTooLong Line exceeds the maximum length.
  82. Link Linking phase.
  83. Name
  84. Path Search paths modifications.
  85. Pattern
  86. Performance
  87. Processing Artifact being compiled.
  88. QuitCalled
  89. Source The source line that triggered a diagnostic
  90. message.
  91. StackTrace
  92. Success, SuccessX Successful compilation of a library or a binary.
  93. User
  94. UserRaw
  95. XDeclaredButNotUsed Unused symbols in the code.
  96. ========================== ============================================
  97. Verbosity levels
  98. ----------------
  99. ===== ============================================
  100. Level Description
  101. ===== ============================================
  102. 0 Minimal output level for the compiler.
  103. 1 Displays compilation of all the compiled files, including those imported
  104. by other modules or through the `compile pragma
  105. <manual.html#implementation-specific-pragmas-compile-pragma>`_.
  106. This is the default level.
  107. 2 Displays compilation statistics, enumerates the dynamic
  108. libraries that will be loaded by the final binary, and dumps to
  109. standard output the result of applying `a filter to the source code
  110. <filters.html>`_ if any filter was used during compilation.
  111. 3 In addition to the previous levels dumps a debug stack trace
  112. for compiler developers.
  113. ===== ============================================
  114. Compile-time symbols
  115. --------------------
  116. Through the `-d:x`:option: or `--define:x`:option: switch you can define compile-time
  117. symbols for conditional compilation. The defined switches can be checked in
  118. source code with the `when statement
  119. <manual.html#statements-and-expressions-when-statement>`_ and
  120. `defined proc <system.html#defined,untyped>`_. The typical use of this switch is
  121. to enable builds in release mode (`-d:release`:option:) where optimizations are
  122. enabled for better performance. Another common use is the `-d:ssl`:option: switch to
  123. activate SSL sockets.
  124. Additionally, you may pass a value along with the symbol: `-d:x=y`:option:
  125. which may be used in conjunction with the `compile-time define
  126. pragmas<manual.html#implementation-specific-pragmas-compileminustime-define-pragmas>`_
  127. to override symbols during build time.
  128. Compile-time symbols are completely **case insensitive** and underscores are
  129. ignored too. `--define:FOO`:option: and `--define:foo`:option: are identical.
  130. Compile-time symbols starting with the `nim` prefix are reserved for the
  131. implementation and should not be used elsewhere.
  132. ========================== ============================================
  133. Name Description
  134. ========================== ============================================
  135. nimStdSetjmp Use the standard `setjmp()/longjmp()` library
  136. functions for setjmp-based exceptions. This is
  137. the default on most platforms.
  138. nimSigSetjmp Use `sigsetjmp()/siglongjmp()` for setjmp-based exceptions.
  139. nimRawSetjmp Use `_setjmp()/_longjmp()` on POSIX and `_setjmp()/longjmp()`
  140. on Windows, for setjmp-based exceptions. It's the default on
  141. BSDs and BSD-like platforms, where it's significantly faster
  142. than the standard functions.
  143. nimBuiltinSetjmp Use `__builtin_setjmp()/__builtin_longjmp()` for setjmp-based
  144. exceptions. This will not work if an exception is being thrown
  145. and caught inside the same procedure. Useful for benchmarking.
  146. ========================== ============================================
  147. Configuration files
  148. -------------------
  149. **Note:** The *project file name* is the name of the ``.nim`` file that is
  150. passed as a command-line argument to the compiler.
  151. The `nim`:cmd: executable processes configuration files in the following
  152. directories (in this order; later files overwrite previous settings):
  153. 1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or
  154. ``<Nim's installation directory>\config\nim.cfg`` (Windows).
  155. This file can be skipped with the `--skipCfg`:option: command line option.
  156. 2) If environment variable `XDG_CONFIG_HOME` is defined,
  157. ``$XDG_CONFIG_HOME/nim/nim.cfg`` or ``~/.config/nim/nim.cfg`` (POSIX) or
  158. ``%APPDATA%/nim/nim.cfg`` (Windows).
  159. This file can be skipped with the `--skipUserCfg`:option: command line
  160. option.
  161. 3) ``$parentDir/nim.cfg`` where ``$parentDir`` stands for any parent
  162. directory of the project file's path.
  163. These files can be skipped with the `--skipParentCfg`:option:
  164. command-line option.
  165. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project
  166. file's path.
  167. This file can be skipped with the `--skipProjCfg`:option:
  168. command-line option.
  169. 5) A project can also have a project-specific configuration file named
  170. ``$project.nim.cfg`` that resides in the same directory as ``$project.nim``.
  171. This file can be skipped with the `--skipProjCfg`:option:
  172. command-line option.
  173. Command-line settings have priority over configuration file settings.
  174. The default build of a project is a `debug build`:idx:. To compile a
  175. `release build`:idx: define the `release` symbol:
  176. .. code:: cmd
  177. nim c -d:release myproject.nim
  178. To compile a `dangerous release build`:idx: define the `danger` symbol:
  179. .. code:: cmd
  180. nim c -d:danger myproject.nim
  181. Search path handling
  182. --------------------
  183. Nim has the concept of a global search path (PATH) that is queried to
  184. determine where to find imported modules or include files. If multiple files are
  185. found an ambiguity error is produced.
  186. `nim dump`:cmd: shows the contents of the PATH.
  187. However before the PATH is used the current directory is checked for the
  188. file's existence. So if PATH contains ``$lib`` and ``$lib/bar`` and the
  189. directory structure looks like this::
  190. $lib/x.nim
  191. $lib/bar/x.nim
  192. foo/x.nim
  193. foo/main.nim
  194. other.nim
  195. And `main` imports `x`, `foo/x` is imported. If `other` imports `x`
  196. then both ``$lib/x.nim`` and ``$lib/bar/x.nim`` match but ``$lib/x.nim`` is used
  197. as it is the first match.
  198. Generated C code directory
  199. --------------------------
  200. The generated files that Nim produces all go into a subdirectory called
  201. ``nimcache``. Its full path is
  202. - ``$XDG_CACHE_HOME/nim/$projectname(_r|_d)`` or ``~/.cache/nim/$projectname(_r|_d)``
  203. on Posix
  204. - ``$HOME\nimcache\$projectname(_r|_d)`` on Windows.
  205. The `_r` suffix is used for release builds, `_d` is for debug builds.
  206. This makes it easy to delete all generated files.
  207. The `--nimcache`:option:
  208. `compiler switch <#compiler-usage-commandminusline-switches>`_ can be used to
  209. to change the ``nimcache`` directory.
  210. However, the generated C code is not platform-independent. C code generated for
  211. Linux does not compile on Windows, for instance. The comment on top of the
  212. C file lists the OS, CPU, and CC the file has been compiled for.
  213. Compiler Selection
  214. ==================
  215. To change the compiler from the default compiler (at the command line):
  216. .. code:: cmd
  217. nim c --cc:llvm_gcc --compile_only myfile.nim
  218. This uses the configuration defined in ``config\nim.cfg`` for `llvm_gcc`:cmd:.
  219. If nimcache already contains compiled code from a different compiler for the same project,
  220. add the `-f`:option: flag to force all files to be recompiled.
  221. The default compiler is defined at the top of ``config\nim.cfg``.
  222. Changing this setting affects the compiler used by `koch`:cmd: to (re)build Nim.
  223. To use the `CC` environment variable, use `nim c --cc:env myfile.nim`:cmd:.
  224. To use the `CXX` environment variable, use `nim cpp --cc:env myfile.nim`:cmd:.
  225. `--cc:env`:option: is available since Nim version 1.4.
  226. Cross-compilation
  227. =================
  228. To cross compile, use for example:
  229. .. code:: cmd
  230. nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim
  231. Then move the C code and the compile script `compile_myproject.sh`:cmd: to your
  232. Linux i386 machine and run the script.
  233. Another way is to make Nim invoke a cross compiler toolchain:
  234. .. code:: cmd
  235. nim c --cpu:arm --os:linux myproject.nim
  236. For cross compilation, the compiler invokes a C compiler named
  237. like `$cpu.$os.$cc` (for example arm.linux.gcc) and the configuration
  238. system is used to provide meaningful defaults. For example for `ARM` your
  239. configuration file should contain something like::
  240. arm.linux.gcc.path = "/usr/bin"
  241. arm.linux.gcc.exe = "arm-linux-gcc"
  242. arm.linux.gcc.linkerexe = "arm-linux-gcc"
  243. Cross-compilation for Windows
  244. =============================
  245. To cross-compile for Windows from Linux or macOS using the MinGW-w64 toolchain:
  246. .. code:: cmd
  247. nim c -d:mingw myproject.nim
  248. # `nim r` also works, running the binary via `wine` or `wine64`:
  249. nim r -d:mingw --eval:'import os; echo "a" / "b"'
  250. Use `--cpu:i386`:option: or `--cpu:amd64`:option: to switch the CPU architecture.
  251. The MinGW-w64 toolchain can be installed as follows:
  252. .. code:: cmd
  253. apt install mingw-w64 # Ubuntu
  254. yum install mingw32-gcc
  255. yum install mingw64-gcc # CentOS - requires EPEL
  256. brew install mingw-w64 # OSX
  257. Cross-compilation for Android
  258. =============================
  259. There are two ways to compile for Android: terminal programs (Termux) and with
  260. the NDK (Android Native Development Kit).
  261. The first one is to treat Android as a simple Linux and use
  262. `Termux <https://wiki.termux.com>`_ to connect and run the Nim compiler
  263. directly on android as if it was Linux. These programs are console-only
  264. programs that can't be distributed in the Play Store.
  265. Use regular `nim c`:cmd: inside termux to make Android terminal programs.
  266. Normal Android apps are written in Java, to use Nim inside an Android app
  267. you need a small Java stub that calls out to a native library written in
  268. Nim using the `NDK <https://developer.android.com/ndk>`_. You can also use
  269. `native-activity <https://developer.android.com/ndk/samples/sample_na>`_
  270. to have the Java stub be auto-generated for you.
  271. Use `nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on`:cmd: to
  272. generate the C source files you need to include in your Android Studio
  273. project. Add the generated C files to CMake build script in your Android
  274. project. Then do the final compile with Android Studio which uses Gradle
  275. to call CMake to compile the project.
  276. Because Nim is part of a library it can't have its own C-style `main()`:c:
  277. so you would need to define your own `android_main`:c: and init the Java
  278. environment, or use a library like SDL2 or GLFM to do it. After the Android
  279. stuff is done, it's very important to call `NimMain()`:c: in order to
  280. initialize Nim's garbage collector and to run the top level statements
  281. of your program.
  282. .. code-block:: Nim
  283. proc NimMain() {.importc.}
  284. proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
  285. NimMain() # initialize garbage collector memory, types and stack
  286. The name `NimMain` can be influenced via the `--nimMainPrefix:prefix` switch.
  287. Use `--nimMainPrefix:MyLib` and the function to call is named `MyLibNimMain`.
  288. Cross-compilation for iOS
  289. =========================
  290. To cross-compile for iOS you need to be on a macOS computer and use XCode.
  291. Normal languages for iOS development are Swift and Objective C. Both of these
  292. use LLVM and can be compiled into object files linked together with C, C++
  293. or Objective C code produced by Nim.
  294. Use `nim c -c --os:ios --noMain:on`:cmd: to generate C files and include them in
  295. your XCode project. Then you can use XCode to compile, link, package and
  296. sign everything.
  297. Because Nim is part of a library it can't have its own C-style `main()`:c: so you
  298. would need to define `main` that calls `autoreleasepool` and
  299. `UIApplicationMain` to do it, or use a library like SDL2 or GLFM. After
  300. the iOS setup is done, it's very important to call `NimMain()`:c: to
  301. initialize Nim's garbage collector and to run the top-level statements
  302. of your program.
  303. .. code-block:: Nim
  304. proc NimMain() {.importc.}
  305. proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
  306. NimMain() # initialize garbage collector memory, types and stack
  307. Note: XCode's "make clean" gets confused about the generated nim.c files,
  308. so you need to clean those files manually to do a clean build.
  309. The name `NimMain` can be influenced via the `--nimMainPrefix:prefix` switch.
  310. Use `--nimMainPrefix:MyLib` and the function to call is named `MyLibNimMain`.
  311. Cross-compilation for Nintendo Switch
  312. =====================================
  313. Simply add `--os:nintendoswitch`:option:
  314. to your usual `nim c`:cmd: or `nim cpp`:cmd: command and set the `passC`:option:
  315. and `passL`:option: command line switches to something like:
  316. .. code-block:: cmd
  317. nim c ... --d:nimAllocPagesViaMalloc --mm:orc --passC="-I$DEVKITPRO/libnx/include" ...
  318. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  319. or setup a ``nim.cfg`` file like so::
  320. #nim.cfg
  321. --mm:orc
  322. --d:nimAllocPagesViaMalloc
  323. --passC="-I$DEVKITPRO/libnx/include"
  324. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  325. The devkitPro setup must be the same as the default with their new installer
  326. `here for Mac/Linux <https://github.com/devkitPro/pacman/releases>`_ or
  327. `here for Windows <https://github.com/devkitPro/installer/releases>`_.
  328. For example, with the above-mentioned config:
  329. .. code:: cmd
  330. nim c --os:nintendoswitch switchhomebrew.nim
  331. This will generate a file called ``switchhomebrew.elf`` which can then be turned into
  332. an nro file with the `elf2nro`:cmd: tool in the devkitPro release. Examples can be found at
  333. `the nim-libnx github repo <https://github.com/jyapayne/nim-libnx.git>`_.
  334. There are a few things that don't work because the devkitPro libraries don't support them.
  335. They are:
  336. 1. Waiting for a subprocess to finish. A subprocess can be started, but right
  337. now it can't be waited on, which sort of makes subprocesses a bit hard to use
  338. 2. Dynamic calls. Switch OS (Horizon) doesn't support dynamic libraries, so dlopen/dlclose are not available.
  339. 3. mqueue. Sadly there are no mqueue headers.
  340. 4. ucontext. No headers for these either. No coroutines for now :(
  341. 5. nl_types. No headers for this.
  342. 6. As mmap is not supported, the nimAllocPagesViaMalloc option has to be used.
  343. DLL generation
  344. ==============
  345. Nim supports the generation of DLLs. However, there must be only one
  346. instance of the GC per process/address space. This instance is contained in
  347. ``nimrtl.dll``. This means that every generated Nim DLL depends
  348. on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command:
  349. .. code:: cmd
  350. nim c -d:release lib/nimrtl.nim
  351. To link against ``nimrtl.dll`` use the command:
  352. .. code:: cmd
  353. nim c -d:useNimRtl myprog.nim
  354. **Note**: Currently the creation of ``nimrtl.dll`` with thread support has
  355. never been tested and is unlikely to work!
  356. Additional compilation switches
  357. ===============================
  358. The standard library supports a growing number of `useX` conditional defines
  359. affecting how some features are implemented. This section tries to give a
  360. complete list.
  361. ====================== =========================================================
  362. Define Effect
  363. ====================== =========================================================
  364. `release` Turns on the optimizer.
  365. More aggressive optimizations are possible, e.g.:
  366. `--passC:-ffast-math`:option: (but see issue #10305)
  367. `danger` Turns off all runtime checks and turns on the optimizer.
  368. `useFork` Makes `osproc` use `fork`:c: instead of `posix_spawn`:c:.
  369. `useNimRtl` Compile and link against ``nimrtl.dll``.
  370. `useMalloc` Makes Nim use C's `malloc`:idx: instead of Nim's
  371. own memory manager, albeit prefixing each allocation with
  372. its size to support clearing memory on reallocation.
  373. This only works with `--mm:none`:option:,
  374. `--mm:arc`:option: and `--mm:orc`:option:.
  375. `useRealtimeGC` Enables support of Nim's GC for *soft* realtime
  376. systems. See the documentation of the `mm <mm.html>`_
  377. for further information.
  378. `logGC` Enable GC logging to stdout.
  379. `nodejs` The JS target is actually ``node.js``.
  380. `ssl` Enables OpenSSL support for the sockets module.
  381. `memProfiler` Enables memory profiling for the native GC.
  382. `uClibc` Use uClibc instead of libc. (Relevant for Unix-like OSes)
  383. `checkAbi` When using types from C headers, add checks that compare
  384. what's in the Nim file with what's in the C header.
  385. This may become enabled by default in the future.
  386. `tempDir` This symbol takes a string as its value, like
  387. `--define:tempDir:/some/temp/path`:option: to override
  388. the temporary directory returned by `os.getTempDir()`.
  389. The value **should** end with a directory separator
  390. character. (Relevant for the Android platform)
  391. `useShPath` This symbol takes a string as its value, like
  392. `--define:useShPath:/opt/sh/bin/sh`:option: to override
  393. the path for the `sh`:cmd: binary, in cases where it is
  394. not located in the default location ``/bin/sh``.
  395. `noSignalHandler` Disable the crash handler from ``system.nim``.
  396. `globalSymbols` Load all `{.dynlib.}` libraries with the `RTLD_GLOBAL`:c:
  397. flag on Posix systems to resolve symbols in subsequently
  398. loaded libraries.
  399. ====================== =========================================================
  400. Additional Features
  401. ===================
  402. This section describes Nim's additional features that are not listed in the
  403. Nim manual. Some of the features here only make sense for the C code
  404. generator and are subject to change.
  405. LineDir option
  406. --------------
  407. The `--lineDir`:option: option can be turned on or off. If turned on the
  408. generated C code contains `#line`:c: directives. This may be helpful for
  409. debugging with GDB.
  410. StackTrace option
  411. -----------------
  412. If the `--stackTrace`:option: option is turned on, the generated C contains code to
  413. ensure that proper stack traces are given if the program crashes or some uncaught exception is raised.
  414. LineTrace option
  415. ----------------
  416. The `--lineTrace`:option: option implies the `stackTrace`:option: option.
  417. If turned on,
  418. the generated C contains code to ensure that proper stack traces with line
  419. number information are given if the program crashes or an uncaught exception
  420. is raised.
  421. DynlibOverride
  422. ==============
  423. By default Nim's `dynlib` pragma causes the compiler to generate
  424. `GetProcAddress`:cpp: (or their Unix counterparts)
  425. calls to bind to a DLL. With the `dynlibOverride`:option: command line switch this
  426. can be prevented and then via `--passL`:option: the static library can be linked
  427. against. For instance, to link statically against Lua this command might work
  428. on Linux:
  429. .. code:: cmd
  430. nim c --dynlibOverride:lua --passL:liblua.lib program.nim
  431. Backend language options
  432. ========================
  433. The typical compiler usage involves using the `compile`:option: or `c`:option:
  434. command to transform a ``.nim`` file into one or more ``.c`` files which are then
  435. compiled with the platform's C compiler into a static binary. However, there
  436. are other commands to compile to C++, Objective-C, or JavaScript. More details
  437. can be read in the `Nim Backend Integration document <backends.html>`_.
  438. Nim documentation tools
  439. =======================
  440. Nim provides the `doc`:idx: command to generate HTML
  441. documentation from ``.nim`` source files. Only exported symbols will appear in
  442. the output. For more details `see the docgen documentation <docgen.html>`_.
  443. Nim idetools integration
  444. ========================
  445. Nim provides language integration with external IDEs through the
  446. idetools command. See the documentation of `idetools <idetools.html>`_
  447. for further information.
  448. ..
  449. Nim interactive mode
  450. ====================
  451. The Nim compiler supports an interactive mode. This is also known as
  452. a `REPL`:idx: (*read eval print loop*). If Nim has been built with the
  453. `-d:nimUseLinenoise` switch, it uses the GNU readline library for terminal
  454. input management. To start Nim in interactive mode use the command
  455. `nim secret`. To quit use the `quit()` command. To determine whether an input
  456. line is an incomplete statement to be continued these rules are used:
  457. 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace).
  458. 2. The line starts with a space (indentation).
  459. 3. The line is within a triple quoted string literal. However, the detection
  460. does not work if the line contains more than one `"""`.
  461. Nim for embedded systems
  462. ========================
  463. While the default Nim configuration is targeted for optimal performance on
  464. modern PC hardware and operating systems with ample memory, it is very well
  465. possible to run Nim code and a good part of the Nim standard libraries on small
  466. embedded microprocessors with only a few kilobytes of memory.
  467. A good start is to use the `any` operating target together with the
  468. `malloc` memory allocator and the `arc` garbage collector. For example:
  469. .. code:: cmd
  470. nim c --os:any --mm:arc -d:useMalloc [...] x.nim
  471. - `--mm:arc`:option: will enable the reference counting memory management instead
  472. of the default garbage collector. This enables Nim to use heap memory which
  473. is required for strings and seqs, for example.
  474. - The `--os:any`:option: target makes sure Nim does not depend on any specific
  475. operating system primitives. Your platform should support only some basic
  476. ANSI C library `stdlib` and `stdio` functions which should be available
  477. on almost any platform.
  478. - The `-d:useMalloc`:option: option configures Nim to use only the standard C memory
  479. manage primitives `malloc()`:c:, `free()`:c:, `realloc()`:c:.
  480. If your platform does not provide these functions it should be trivial to
  481. provide an implementation for them and link these to your program.
  482. For targets with very restricted memory, it might be beneficial to pass some
  483. additional flags to both the Nim compiler and the C compiler and/or linker
  484. to optimize the build for size. For example, the following flags can be used
  485. when targeting a gcc compiler:
  486. `--opt:size --passC:-flto --passL:-flto`:option:
  487. The `--opt:size`:option: flag instructs Nim to optimize code generation for small
  488. size (with the help of the C compiler), the `-flto`:option: flags enable link-time
  489. optimization in the compiler and linker.
  490. Check the `Cross-compilation`_ section for instructions on how to compile the
  491. program for your target.
  492. nimAllocPagesViaMalloc
  493. ----------------------
  494. Nim's default allocator is based on TLSF, this algorithm was designed for embedded
  495. devices. This allocator gets blocks/pages of memory via a currently undocumented
  496. `osalloc` API which usually uses POSIX's `mmap` call. On many environments `mmap`
  497. is not available but C's `malloc` is. You can use the `nimAllocPagesViaMalloc`
  498. define to use `malloc` instead of `mmap`. `nimAllocPagesViaMalloc` is currently
  499. only supported with `--mm:arc` or `--mm:orc`. (Since version 1.6)
  500. nimPage256 / nimPage512 / nimPage1k
  501. ===================================
  502. Adjust the page size for Nim's GC allocator. This enables using
  503. `nimAllocPagesViaMalloc` on devices with less RAM. The default
  504. page size requires too much RAM to work.
  505. Recommended settings:
  506. - < 32 kB of RAM use `nimPage256`
  507. - < 512 kB of RAM use `nimPage512`
  508. - < 2 MB of RAM use `nimPage1k`
  509. Initial testing hasn't shown much difference between 512B or 1kB page sizes
  510. in terms of performance or latency. Using `nimPages256` will limit the
  511. total amount of allocatable RAM.
  512. nimMemAlignTiny
  513. ===============
  514. Sets `MemAlign` to `4` bytes which reduces the memory alignment
  515. to better match some embedded devices.
  516. Thread stack size
  517. =================
  518. Nim's thread API provides a simple wrapper around more advanced
  519. RTOS task features. Customizing the stack size and stack guard size can
  520. be done by setting `-d:nimThreadStackSize=16384` or `-d:nimThreadStackGuard=32`.
  521. Currently only Zephyr and FreeRTOS support these configurations.
  522. Nim for realtime systems
  523. ========================
  524. See the `--mm:arc` or `--mm:orc` memory management settings in `MM <mm.html>`_ for further
  525. information.
  526. Signal handling in Nim
  527. ======================
  528. The Nim programming language has no concept of Posix's signal handling
  529. mechanisms. However, the standard library offers some rudimentary support
  530. for signal handling, in particular, segmentation faults are turned into
  531. fatal errors that produce a stack trace. This can be disabled with the
  532. `-d:noSignalHandler`:option: switch.
  533. Optimizing for Nim
  534. ==================
  535. Nim has no separate optimizer, but the C code that is produced is very
  536. efficient. Most C compilers have excellent optimizers, so usually it is
  537. not needed to optimize one's code. Nim has been designed to encourage
  538. efficient code: The most readable code in Nim is often the most efficient
  539. too.
  540. However, sometimes one has to optimize. Do it in the following order:
  541. 1. switch off the embedded debugger (it is **slow**!)
  542. 2. turn on the optimizer and turn off runtime checks
  543. 3. profile your code to find where the bottlenecks are
  544. 4. try to find a better algorithm
  545. 5. do low-level optimizations
  546. This section can only help you with the last item.
  547. Optimizing string handling
  548. --------------------------
  549. String assignments are sometimes expensive in Nim: They are required to
  550. copy the whole string. However, the compiler is often smart enough to not copy
  551. strings. Due to the argument passing semantics, strings are never copied when
  552. passed to subroutines. The compiler does not copy strings that are a result of
  553. a procedure call, because the callee returns a new string anyway.
  554. Thus it is efficient to do:
  555. .. code-block:: Nim
  556. var s = procA() # assignment will not copy the string; procA allocates a new
  557. # string already
  558. However, it is not efficient to do:
  559. .. code-block:: Nim
  560. var s = varA # assignment has to copy the whole string into a new buffer!
  561. For `let` symbols a copy is not always necessary:
  562. .. code-block:: Nim
  563. let s = varA # may only copy a pointer if it safe to do so
  564. If you know what you're doing, you can also mark single-string (or sequence)
  565. objects as `shallow`:idx:\:
  566. .. code-block:: Nim
  567. var s = "abc"
  568. shallow(s) # mark 's' as a shallow string
  569. var x = s # now might not copy the string!
  570. Usage of `shallow` is always safe once you know the string won't be modified
  571. anymore, similar to Ruby's `freeze`:idx:.
  572. The compiler optimizes string case statements: A hashing scheme is used for them
  573. if several different string constants are used. So code like this is reasonably
  574. efficient:
  575. .. code-block:: Nim
  576. case normalize(k.key)
  577. of "name": c.name = v
  578. of "displayname": c.displayName = v
  579. of "version": c.version = v
  580. of "os": c.oses = split(v, {';'})
  581. of "cpu": c.cpus = split(v, {';'})
  582. of "authors": c.authors = split(v, {';'})
  583. of "description": c.description = v
  584. of "app":
  585. case normalize(v)
  586. of "console": c.app = appConsole
  587. of "gui": c.app = appGUI
  588. else: quit(errorStr(p, "expected: console or gui"))
  589. of "license": c.license = UnixToNativePath(k.value)
  590. else: quit(errorStr(p, "unknown variable: " & k.key))