nimc.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. Configuration files
  133. -------------------
  134. **Note:** The *project file name* is the name of the ``.nim`` file that is
  135. passed as a command-line argument to the compiler.
  136. The `nim`:cmd: executable processes configuration files in the following
  137. directories (in this order; later files overwrite previous settings):
  138. 1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or
  139. ``<Nim's installation directory>\config\nim.cfg`` (Windows).
  140. This file can be skipped with the `--skipCfg`:option: command line option.
  141. 2) If environment variable `XDG_CONFIG_HOME` is defined,
  142. ``$XDG_CONFIG_HOME/nim/nim.cfg`` or ``~/.config/nim/nim.cfg`` (POSIX) or
  143. ``%APPDATA%/nim/nim.cfg`` (Windows).
  144. This file can be skipped with the `--skipUserCfg`:option: command line
  145. option.
  146. 3) ``$parentDir/nim.cfg`` where ``$parentDir`` stands for any parent
  147. directory of the project file's path.
  148. These files can be skipped with the `--skipParentCfg`:option:
  149. command-line option.
  150. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project
  151. file's path.
  152. This file can be skipped with the `--skipProjCfg`:option:
  153. command-line option.
  154. 5) A project can also have a project-specific configuration file named
  155. ``$project.nim.cfg`` that resides in the same directory as ``$project.nim``.
  156. This file can be skipped with the `--skipProjCfg`:option:
  157. command-line option.
  158. Command-line settings have priority over configuration file settings.
  159. The default build of a project is a `debug build`:idx:. To compile a
  160. `release build`:idx: define the `release` symbol:
  161. .. code:: cmd
  162. nim c -d:release myproject.nim
  163. To compile a `dangerous release build`:idx: define the `danger` symbol:
  164. .. code:: cmd
  165. nim c -d:danger myproject.nim
  166. Search path handling
  167. --------------------
  168. Nim has the concept of a global search path (PATH) that is queried to
  169. determine where to find imported modules or include files. If multiple files are
  170. found an ambiguity error is produced.
  171. `nim dump`:cmd: shows the contents of the PATH.
  172. However before the PATH is used the current directory is checked for the
  173. file's existence. So if PATH contains ``$lib`` and ``$lib/bar`` and the
  174. directory structure looks like this::
  175. $lib/x.nim
  176. $lib/bar/x.nim
  177. foo/x.nim
  178. foo/main.nim
  179. other.nim
  180. And `main` imports `x`, `foo/x` is imported. If `other` imports `x`
  181. then both ``$lib/x.nim`` and ``$lib/bar/x.nim`` match but ``$lib/x.nim`` is used
  182. as it is the first match.
  183. Generated C code directory
  184. --------------------------
  185. The generated files that Nim produces all go into a subdirectory called
  186. ``nimcache``. Its full path is
  187. - ``$XDG_CACHE_HOME/nim/$projectname(_r|_d)`` or ``~/.cache/nim/$projectname(_r|_d)``
  188. on Posix
  189. - ``$HOME\nimcache\$projectname(_r|_d)`` on Windows.
  190. The `_r` suffix is used for release builds, `_d` is for debug builds.
  191. This makes it easy to delete all generated files.
  192. The `--nimcache`:option:
  193. `compiler switch <#compiler-usage-commandminusline-switches>`_ can be used to
  194. to change the ``nimcache`` directory.
  195. However, the generated C code is not platform-independent. C code generated for
  196. Linux does not compile on Windows, for instance. The comment on top of the
  197. C file lists the OS, CPU, and CC the file has been compiled for.
  198. Compiler Selection
  199. ==================
  200. To change the compiler from the default compiler (at the command line):
  201. .. code:: cmd
  202. nim c --cc:llvm_gcc --compile_only myfile.nim
  203. This uses the configuration defined in ``config\nim.cfg`` for `llvm_gcc`:cmd:.
  204. If nimcache already contains compiled code from a different compiler for the same project,
  205. add the `-f`:option: flag to force all files to be recompiled.
  206. The default compiler is defined at the top of ``config\nim.cfg``.
  207. Changing this setting affects the compiler used by `koch`:cmd: to (re)build Nim.
  208. To use the `CC` environment variable, use `nim c --cc:env myfile.nim`:cmd:.
  209. To use the `CXX` environment variable, use `nim cpp --cc:env myfile.nim`:cmd:.
  210. `--cc:env`:option: is available since Nim version 1.4.
  211. Cross-compilation
  212. =================
  213. To cross compile, use for example:
  214. .. code:: cmd
  215. nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim
  216. Then move the C code and the compile script `compile_myproject.sh`:cmd: to your
  217. Linux i386 machine and run the script.
  218. Another way is to make Nim invoke a cross compiler toolchain:
  219. .. code:: cmd
  220. nim c --cpu:arm --os:linux myproject.nim
  221. For cross compilation, the compiler invokes a C compiler named
  222. like `$cpu.$os.$cc` (for example arm.linux.gcc) and the configuration
  223. system is used to provide meaningful defaults. For example for `ARM` your
  224. configuration file should contain something like::
  225. arm.linux.gcc.path = "/usr/bin"
  226. arm.linux.gcc.exe = "arm-linux-gcc"
  227. arm.linux.gcc.linkerexe = "arm-linux-gcc"
  228. Cross-compilation for Windows
  229. =============================
  230. To cross-compile for Windows from Linux or macOS using the MinGW-w64 toolchain:
  231. .. code:: cmd
  232. nim c -d:mingw myproject.nim
  233. # `nim r` also works, running the binary via `wine` or `wine64`:
  234. nim r -d:mingw --eval:'import os; echo "a" / "b"'
  235. Use `--cpu:i386`:option: or `--cpu:amd64`:option: to switch the CPU architecture.
  236. The MinGW-w64 toolchain can be installed as follows:
  237. .. code:: cmd
  238. apt install mingw-w64 # Ubuntu
  239. yum install mingw32-gcc
  240. yum install mingw64-gcc # CentOS - requires EPEL
  241. brew install mingw-w64 # OSX
  242. Cross-compilation for Android
  243. =============================
  244. There are two ways to compile for Android: terminal programs (Termux) and with
  245. the NDK (Android Native Development Kit).
  246. The first one is to treat Android as a simple Linux and use
  247. `Termux <https://wiki.termux.com>`_ to connect and run the Nim compiler
  248. directly on android as if it was Linux. These programs are console-only
  249. programs that can't be distributed in the Play Store.
  250. Use regular `nim c`:cmd: inside termux to make Android terminal programs.
  251. Normal Android apps are written in Java, to use Nim inside an Android app
  252. you need a small Java stub that calls out to a native library written in
  253. Nim using the `NDK <https://developer.android.com/ndk>`_. You can also use
  254. `native-activity <https://developer.android.com/ndk/samples/sample_na>`_
  255. to have the Java stub be auto-generated for you.
  256. Use `nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on`:cmd: to
  257. generate the C source files you need to include in your Android Studio
  258. project. Add the generated C files to CMake build script in your Android
  259. project. Then do the final compile with Android Studio which uses Gradle
  260. to call CMake to compile the project.
  261. Because Nim is part of a library it can't have its own C-style `main()`:c:
  262. so you would need to define your own `android_main`:c: and init the Java
  263. environment, or use a library like SDL2 or GLFM to do it. After the Android
  264. stuff is done, it's very important to call `NimMain()`:c: in order to
  265. initialize Nim's garbage collector and to run the top level statements
  266. of your program.
  267. .. code-block:: Nim
  268. proc NimMain() {.importc.}
  269. proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
  270. NimMain() # initialize garbage collector memory, types and stack
  271. Cross-compilation for iOS
  272. =========================
  273. To cross-compile for iOS you need to be on a macOS computer and use XCode.
  274. Normal languages for iOS development are Swift and Objective C. Both of these
  275. use LLVM and can be compiled into object files linked together with C, C++
  276. or Objective C code produced by Nim.
  277. Use `nim c -c --os:ios --noMain:on`:cmd: to generate C files and include them in
  278. your XCode project. Then you can use XCode to compile, link, package and
  279. sign everything.
  280. Because Nim is part of a library it can't have its own C-style `main()`:c: so you
  281. would need to define `main` that calls `autoreleasepool` and
  282. `UIApplicationMain` to do it, or use a library like SDL2 or GLFM. After
  283. the iOS setup is done, it's very important to call `NimMain()`:c: to
  284. initialize Nim's garbage collector and to run the top-level statements
  285. of your program.
  286. .. code-block:: Nim
  287. proc NimMain() {.importc.}
  288. proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
  289. NimMain() # initialize garbage collector memory, types and stack
  290. Note: XCode's "make clean" gets confused about the generated nim.c files,
  291. so you need to clean those files manually to do a clean build.
  292. Cross-compilation for Nintendo Switch
  293. =====================================
  294. Simply add `--os:nintendoswitch`:option:
  295. to your usual `nim c`:cmd: or `nim cpp`:cmd: command and set the `passC`:option:
  296. and `passL`:option: command line switches to something like:
  297. .. code-block:: cmd
  298. nim c ... --d:nimAllocPagesViaMalloc --gc:orc --passC="-I$DEVKITPRO/libnx/include" ...
  299. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  300. or setup a ``nim.cfg`` file like so::
  301. #nim.cfg
  302. --gc:orc
  303. --d:nimAllocPagesViaMalloc
  304. --passC="-I$DEVKITPRO/libnx/include"
  305. --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
  306. The devkitPro setup must be the same as the default with their new installer
  307. `here for Mac/Linux <https://github.com/devkitPro/pacman/releases>`_ or
  308. `here for Windows <https://github.com/devkitPro/installer/releases>`_.
  309. For example, with the above-mentioned config:
  310. .. code:: cmd
  311. nim c --os:nintendoswitch switchhomebrew.nim
  312. This will generate a file called ``switchhomebrew.elf`` which can then be turned into
  313. an nro file with the `elf2nro`:cmd: tool in the devkitPro release. Examples can be found at
  314. `the nim-libnx github repo <https://github.com/jyapayne/nim-libnx.git>`_.
  315. There are a few things that don't work because the devkitPro libraries don't support them.
  316. They are:
  317. 1. Waiting for a subprocess to finish. A subprocess can be started, but right
  318. now it can't be waited on, which sort of makes subprocesses a bit hard to use
  319. 2. Dynamic calls. Switch OS (Horizon) doesn't support dynamic libraries, so dlopen/dlclose are not available.
  320. 3. mqueue. Sadly there are no mqueue headers.
  321. 4. ucontext. No headers for these either. No coroutines for now :(
  322. 5. nl_types. No headers for this.
  323. 6. As mmap is not supported, the nimAllocPagesViaMalloc option has to be used.
  324. DLL generation
  325. ==============
  326. Nim supports the generation of DLLs. However, there must be only one
  327. instance of the GC per process/address space. This instance is contained in
  328. ``nimrtl.dll``. This means that every generated Nim DLL depends
  329. on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command:
  330. .. code:: cmd
  331. nim c -d:release lib/nimrtl.nim
  332. To link against ``nimrtl.dll`` use the command:
  333. .. code:: cmd
  334. nim c -d:useNimRtl myprog.nim
  335. **Note**: Currently the creation of ``nimrtl.dll`` with thread support has
  336. never been tested and is unlikely to work!
  337. Additional compilation switches
  338. ===============================
  339. The standard library supports a growing number of `useX` conditional defines
  340. affecting how some features are implemented. This section tries to give a
  341. complete list.
  342. ====================== =========================================================
  343. Define Effect
  344. ====================== =========================================================
  345. `release` Turns on the optimizer.
  346. More aggressive optimizations are possible, e.g.:
  347. `--passC:-ffast-math`:option: (but see issue #10305)
  348. `danger` Turns off all runtime checks and turns on the optimizer.
  349. `useFork` Makes `osproc` use `fork`:c: instead of `posix_spawn`:c:.
  350. `useNimRtl` Compile and link against ``nimrtl.dll``.
  351. `useMalloc` Makes Nim use C's `malloc`:idx: instead of Nim's
  352. own memory manager, albeit prefixing each allocation with
  353. its size to support clearing memory on reallocation.
  354. This only works with `--gc:none`:option:,
  355. `--gc:arc`:option: and `--gc:orc`:option:.
  356. `useRealtimeGC` Enables support of Nim's GC for *soft* realtime
  357. systems. See the documentation of the `gc <gc.html>`_
  358. for further information.
  359. `logGC` Enable GC logging to stdout.
  360. `nodejs` The JS target is actually ``node.js``.
  361. `ssl` Enables OpenSSL support for the sockets module.
  362. `memProfiler` Enables memory profiling for the native GC.
  363. `uClibc` Use uClibc instead of libc. (Relevant for Unix-like OSes)
  364. `checkAbi` When using types from C headers, add checks that compare
  365. what's in the Nim file with what's in the C header.
  366. This may become enabled by default in the future.
  367. `tempDir` This symbol takes a string as its value, like
  368. `--define:tempDir:/some/temp/path`:option: to override
  369. the temporary directory returned by `os.getTempDir()`.
  370. The value **should** end with a directory separator
  371. character. (Relevant for the Android platform)
  372. `useShPath` This symbol takes a string as its value, like
  373. `--define:useShPath:/opt/sh/bin/sh`:option: to override
  374. the path for the `sh`:cmd: binary, in cases where it is
  375. not located in the default location ``/bin/sh``.
  376. `noSignalHandler` Disable the crash handler from ``system.nim``.
  377. `globalSymbols` Load all `{.dynlib.}` libraries with the `RTLD_GLOBAL`:c:
  378. flag on Posix systems to resolve symbols in subsequently
  379. loaded libraries.
  380. ====================== =========================================================
  381. Additional Features
  382. ===================
  383. This section describes Nim's additional features that are not listed in the
  384. Nim manual. Some of the features here only make sense for the C code
  385. generator and are subject to change.
  386. LineDir option
  387. --------------
  388. The `--lineDir`:option: option can be turned on or off. If turned on the
  389. generated C code contains `#line`:c: directives. This may be helpful for
  390. debugging with GDB.
  391. StackTrace option
  392. -----------------
  393. If the `--stackTrace`:option: option is turned on, the generated C contains code to
  394. ensure that proper stack traces are given if the program crashes or some uncaught exception is raised.
  395. LineTrace option
  396. ----------------
  397. The `--lineTrace`:option: option implies the `stackTrace`:option: option.
  398. If turned on,
  399. the generated C contains code to ensure that proper stack traces with line
  400. number information are given if the program crashes or an uncaught exception
  401. is raised.
  402. DynlibOverride
  403. ==============
  404. By default Nim's `dynlib` pragma causes the compiler to generate
  405. `GetProcAddress`:cpp: (or their Unix counterparts)
  406. calls to bind to a DLL. With the `dynlibOverride`:option: command line switch this
  407. can be prevented and then via `--passL`:option: the static library can be linked
  408. against. For instance, to link statically against Lua this command might work
  409. on Linux:
  410. .. code:: cmd
  411. nim c --dynlibOverride:lua --passL:liblua.lib program.nim
  412. Backend language options
  413. ========================
  414. The typical compiler usage involves using the `compile`:option: or `c`:option:
  415. command to transform a ``.nim`` file into one or more ``.c`` files which are then
  416. compiled with the platform's C compiler into a static binary. However, there
  417. are other commands to compile to C++, Objective-C, or JavaScript. More details
  418. can be read in the `Nim Backend Integration document <backends.html>`_.
  419. Nim documentation tools
  420. =======================
  421. Nim provides the `doc`:idx: command to generate HTML
  422. documentation from ``.nim`` source files. Only exported symbols will appear in
  423. the output. For more details `see the docgen documentation <docgen.html>`_.
  424. Nim idetools integration
  425. ========================
  426. Nim provides language integration with external IDEs through the
  427. idetools command. See the documentation of `idetools <idetools.html>`_
  428. for further information.
  429. ..
  430. Nim interactive mode
  431. ====================
  432. The Nim compiler supports an interactive mode. This is also known as
  433. a `REPL`:idx: (*read eval print loop*). If Nim has been built with the
  434. `-d:nimUseLinenoise` switch, it uses the GNU readline library for terminal
  435. input management. To start Nim in interactive mode use the command
  436. `nim secret`. To quit use the `quit()` command. To determine whether an input
  437. line is an incomplete statement to be continued these rules are used:
  438. 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace).
  439. 2. The line starts with a space (indentation).
  440. 3. The line is within a triple quoted string literal. However, the detection
  441. does not work if the line contains more than one `"""`.
  442. Nim for embedded systems
  443. ========================
  444. While the default Nim configuration is targeted for optimal performance on
  445. modern PC hardware and operating systems with ample memory, it is very well
  446. possible to run Nim code and a good part of the Nim standard libraries on small
  447. embedded microprocessors with only a few kilobytes of memory.
  448. A good start is to use the `any` operating target together with the
  449. `malloc` memory allocator and the `arc` garbage collector. For example:
  450. .. code:: cmd
  451. nim c --os:any --gc:arc -d:useMalloc [...] x.nim
  452. - `--gc:arc`:option: will enable the reference counting memory management instead
  453. of the default garbage collector. This enables Nim to use heap memory which
  454. is required for strings and seqs, for example.
  455. - The `--os:any`:option: target makes sure Nim does not depend on any specific
  456. operating system primitives. Your platform should support only some basic
  457. ANSI C library `stdlib` and `stdio` functions which should be available
  458. on almost any platform.
  459. - The `-d:useMalloc`:option: option configures Nim to use only the standard C memory
  460. manage primitives `malloc()`:c:, `free()`:c:, `realloc()`:c:.
  461. If your platform does not provide these functions it should be trivial to
  462. provide an implementation for them and link these to your program.
  463. For targets with very restricted memory, it might be beneficial to pass some
  464. additional flags to both the Nim compiler and the C compiler and/or linker
  465. to optimize the build for size. For example, the following flags can be used
  466. when targeting a gcc compiler:
  467. `--opt:size --passC:-flto --passL:-flto`:option:
  468. The `--opt:size`:option: flag instructs Nim to optimize code generation for small
  469. size (with the help of the C compiler), the `-flto`:option: flags enable link-time
  470. optimization in the compiler and linker.
  471. Check the `Cross-compilation`_ section for instructions on how to compile the
  472. program for your target.
  473. nimAllocPagesViaMalloc
  474. ----------------------
  475. Nim's default allocator is based on TLSF, this algorithm was designed for embedded
  476. devices. This allocator gets blocks/pages of memory via a currently undocumented
  477. `osalloc` API which usually uses POSIX's `mmap` call. On many environments `mmap`
  478. is not available but C's `malloc` is. You can use the `nimAllocPagesViaMalloc`
  479. define to use `malloc` instead of `mmap`. `nimAllocPagesViaMalloc` is currently
  480. only supported with `--gc:arc` or `--gc:orc`. (Since version 1.6)
  481. Nim for realtime systems
  482. ========================
  483. See the documentation of Nim's soft realtime `GC <gc.html>`_ for further
  484. information.
  485. Signal handling in Nim
  486. ======================
  487. The Nim programming language has no concept of Posix's signal handling
  488. mechanisms. However, the standard library offers some rudimentary support
  489. for signal handling, in particular, segmentation faults are turned into
  490. fatal errors that produce a stack trace. This can be disabled with the
  491. `-d:noSignalHandler`:option: switch.
  492. Optimizing for Nim
  493. ==================
  494. Nim has no separate optimizer, but the C code that is produced is very
  495. efficient. Most C compilers have excellent optimizers, so usually it is
  496. not needed to optimize one's code. Nim has been designed to encourage
  497. efficient code: The most readable code in Nim is often the most efficient
  498. too.
  499. However, sometimes one has to optimize. Do it in the following order:
  500. 1. switch off the embedded debugger (it is **slow**!)
  501. 2. turn on the optimizer and turn off runtime checks
  502. 3. profile your code to find where the bottlenecks are
  503. 4. try to find a better algorithm
  504. 5. do low-level optimizations
  505. This section can only help you with the last item.
  506. Optimizing string handling
  507. --------------------------
  508. String assignments are sometimes expensive in Nim: They are required to
  509. copy the whole string. However, the compiler is often smart enough to not copy
  510. strings. Due to the argument passing semantics, strings are never copied when
  511. passed to subroutines. The compiler does not copy strings that are a result of
  512. a procedure call, because the callee returns a new string anyway.
  513. Thus it is efficient to do:
  514. .. code-block:: Nim
  515. var s = procA() # assignment will not copy the string; procA allocates a new
  516. # string already
  517. However, it is not efficient to do:
  518. .. code-block:: Nim
  519. var s = varA # assignment has to copy the whole string into a new buffer!
  520. For `let` symbols a copy is not always necessary:
  521. .. code-block:: Nim
  522. let s = varA # may only copy a pointer if it safe to do so
  523. If you know what you're doing, you can also mark single-string (or sequence)
  524. objects as `shallow`:idx:\:
  525. .. code-block:: Nim
  526. var s = "abc"
  527. shallow(s) # mark 's' as a shallow string
  528. var x = s # now might not copy the string!
  529. Usage of `shallow` is always safe once you know the string won't be modified
  530. anymore, similar to Ruby's `freeze`:idx:.
  531. The compiler optimizes string case statements: A hashing scheme is used for them
  532. if several different string constants are used. So code like this is reasonably
  533. efficient:
  534. .. code-block:: Nim
  535. case normalize(k.key)
  536. of "name": c.name = v
  537. of "displayname": c.displayName = v
  538. of "version": c.version = v
  539. of "os": c.oses = split(v, {';'})
  540. of "cpu": c.cpus = split(v, {';'})
  541. of "authors": c.authors = split(v, {';'})
  542. of "description": c.description = v
  543. of "app":
  544. case normalize(v)
  545. of "console": c.app = appConsole
  546. of "gui": c.app = appGUI
  547. else: quit(errorStr(p, "expected: console or gui"))
  548. of "license": c.license = UnixToNativePath(k.value)
  549. else: quit(errorStr(p, "unknown variable: " & k.key))