Massive documentation fixes + copy editing (#15747)

This commit is contained in:
Yanis Zafirópulos 2020-10-29 10:33:47 +01:00 • committed by GitHub
commit 0cae8ef2ca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 401 additions and 411 deletions

View file

@ -3,7 +3,7 @@ API naming design
================= =================
The API is designed to be **easy to use** and consistent. Ease of use is The API is designed to be **easy to use** and consistent. Ease of use is
measured by the number of calls to achieve a concrete high level action. measured by the number of calls to achieve a concrete high-level action.
Naming scheme Naming scheme

View file

@ -15,16 +15,16 @@ Introduction
The `Nim Compiler User Guide <nimc.html>`_ documents the typical The `Nim Compiler User Guide <nimc.html>`_ documents the typical
compiler invocation, using the ``compile`` or ``c`` command to transform a compiler invocation, using the ``compile`` or ``c`` command to transform a
``.nim`` file into one or more ``.c`` files which are then compiled with the ``.nim`` file into one or more ``.c`` files which are then compiled with the
platform's C compiler into a static binary. However there are other commands platform's C compiler into a static binary. However, there are other commands
to compile to C++, Objective-C or JavaScript. This document tries to to compile to C++, Objective-C, or JavaScript. This document tries to
concentrate in a single place all the backend and interfacing options. concentrate in a single place all the backend and interfacing options.
The Nim compiler supports mainly two backend families: the C, C++ and The Nim compiler supports mainly two backend families: the C, C++ and
Objective-C targets and the JavaScript target. `The C like targets Objective-C targets and the JavaScript target. `The C like targets
<#backends-the-c-like-targets>`_ creates source files which can be compiled <#backends-the-c-like-targets>`_ creates source files that can be compiled
into a library or a final executable. `The JavaScript target into a library or a final executable. `The JavaScript target
<#backends-the-javascript-target>`_ can generate a ``.js`` file which you <#backends-the-javascript-target>`_ can generate a ``.js`` file which you
reference from an HTML file or create a `standalone nodejs program reference from an HTML file or create a `standalone Node.js program
<http://nodejs.org>`_. <http://nodejs.org>`_.
On top of generating libraries or standalone applications, Nim offers On top of generating libraries or standalone applications, Nim offers
@ -48,7 +48,7 @@ The most significant difference between these commands is that if you look
into the ``nimcache`` directory you will find ``.c``, ``.cpp`` or ``.m`` into the ``nimcache`` directory you will find ``.c``, ``.cpp`` or ``.m``
files, other than that all of them will produce a native binary for your files, other than that all of them will produce a native binary for your
project. This allows you to take the generated code and place it directly project. This allows you to take the generated code and place it directly
into a project using any of these languages. Here are some typical command into a project using any of these languages. Here are some typical command-
line invocations:: line invocations::
$ nim c hallo.nim $ nim c hallo.nim
@ -56,8 +56,8 @@ line invocations::
$ nim objc hallo.nim $ nim objc hallo.nim
The compiler commands select the target backend, but if needed you can The compiler commands select the target backend, but if needed you can
`specify additional switches for cross compilation `specify additional switches for cross-compilation
<nimc.html#cross-compilation>`_ to select the target CPU, operative system <nimc.html#crossminuscompilation>`_ to select the target CPU, operative system
or compiler/linker commands. or compiler/linker commands.
@ -79,7 +79,7 @@ available. This includes:
* OS-specific operations * OS-specific operations
* threading, coroutines * threading, coroutines
* some modules of the standard library * some modules of the standard library
* proper 64 bit integer arithmetic * proper 64-bit integer arithmetic
To compensate, the standard library has modules `catered to the JS backend To compensate, the standard library has modules `catered to the JS backend
<lib.html#pure-libraries-modules-for-js-backend>`_ <lib.html#pure-libraries-modules-for-js-backend>`_
@ -119,7 +119,7 @@ pragmas to call methods from classes.
Whenever you use any of these pragmas you need to integrate native code into Whenever you use any of these pragmas you need to integrate native code into
your final binary. In the case of JavaScript this is no problem at all, the your final binary. In the case of JavaScript this is no problem at all, the
same html file which hosts the generated JavaScript will likely provide other same HTML file which hosts the generated JavaScript will likely provide other
JavaScript functions which you are importing with ``importc``. JavaScript functions which you are importing with ``importc``.
However, for the C like targets you need to link external code either However, for the C like targets you need to link external code either
@ -167,7 +167,7 @@ With these two files in place, you can run ``nim c -r calculator.nim`` and
the Nim compiler will compile the ``logic.c`` file in addition to the Nim compiler will compile the ``logic.c`` file in addition to
``calculator.nim`` and link both into an executable, which outputs ``10`` when ``calculator.nim`` and link both into an executable, which outputs ``10`` when
run. Another way to link the C file statically and get the same effect would run. Another way to link the C file statically and get the same effect would
be remove the line with the ``compile`` pragma and run the following typical be to remove the line with the ``compile`` pragma and run the following typical
Unix commands:: Unix commands::
$ gcc -c logic.c $ gcc -c logic.c
@ -211,7 +211,7 @@ calculator.nim`` and open ``host.html`` in a browser. If the browser supports
javascript, you should see the value ``10`` in the browser's console. Use the javascript, you should see the value ``10`` in the browser's console. Use the
`dom module <dom.html>`_ for specific DOM querying and modification procs `dom module <dom.html>`_ for specific DOM querying and modification procs
or take a look at `karax <https://github.com/pragmagic/karax>`_ for how to or take a look at `karax <https://github.com/pragmagic/karax>`_ for how to
develop browser based applications. develop browser-based applications.
Backend code calling Nim Backend code calling Nim
@ -220,7 +220,7 @@ Backend code calling Nim
Backend code can interface with Nim code exposed through the `exportc Backend code can interface with Nim code exposed through the `exportc
pragma <manual.html#foreign-function-interface-exportc-pragma>`_. The pragma <manual.html#foreign-function-interface-exportc-pragma>`_. The
``exportc`` pragma is the *generic* way of making Nim symbols available to ``exportc`` pragma is the *generic* way of making Nim symbols available to
the backends. By default the Nim compiler will mangle all the Nim symbols to the backends. By default, the Nim compiler will mangle all the Nim symbols to
avoid any name collision, so the most significant thing the ``exportc`` pragma avoid any name collision, so the most significant thing the ``exportc`` pragma
does is maintain the Nim symbol name, or if specified, use an alternative does is maintain the Nim symbol name, or if specified, use an alternative
symbol for the backend in case the symbol rules don't match. symbol for the backend in case the symbol rules don't match.
@ -233,7 +233,7 @@ the compiler will assume certain types for the return value and parameters
which will likely make your program crash at runtime. which will likely make your program crash at runtime.
The Nim compiler can generate a C interface header through the ``--header`` The Nim compiler can generate a C interface header through the ``--header``
command line switch. The generated header will contain all the exported command-line switch. The generated header will contain all the exported
symbols and the ``NimMain`` proc which you need to call before any other symbols and the ``NimMain`` proc which you need to call before any other
Nim code. Nim code.
@ -322,8 +322,8 @@ from the previous section):
Compile the Nim code to JavaScript with ``nim js -o:fib.js fib.nim`` and Compile the Nim code to JavaScript with ``nim js -o:fib.js fib.nim`` and
open ``mhost.html`` in a browser. If the browser supports javascript, you open ``mhost.html`` in a browser. If the browser supports javascript, you
should see an alert box displaying the text ``Fib for 9 is 34``. As mentioned should see an alert box displaying the text ``Fib for 9 is 34``. As mentioned
earlier, JavaScript doesn't require an initialisation call to ``NimMain`` or earlier, JavaScript doesn't require an initialization call to ``NimMain`` or
similar function and you can call the exported Nim proc directly. a similar function and you can call the exported Nim proc directly.
Nimcache naming logic Nimcache naming logic
@ -333,15 +333,15 @@ The `nimcache`:idx: directory is generated during compilation and will hold
either temporary or final files depending on your backend target. The default either temporary or final files depending on your backend target. The default
name for the directory depends on the used backend and on your OS but you can name for the directory depends on the used backend and on your OS but you can
use the ``--nimcache`` `compiler switch use the ``--nimcache`` `compiler switch
<nimc.html#compiler-usage-command-line-switches>`_ to change it. <nimc.html#compiler-usage-commandminusline-switches>`_ to change it.
Memory management Memory management
================= =================
In the previous sections the ``NimMain()`` function reared its head. Since In the previous sections, the ``NimMain()`` function reared its head. Since
JavaScript already provides automatic memory management, you can freely pass JavaScript already provides automatic memory management, you can freely pass
objects between the two language without problems. In C and derivate languages objects between the two languages without problems. In C and derivate languages
you need to be careful about what you do and how you share memory. The you need to be careful about what you do and how you share memory. The
previous examples only dealt with simple scalar values, but passing a Nim previous examples only dealt with simple scalar values, but passing a Nim
string to C, or reading back a C string in Nim already requires you to be string to C, or reading back a C string in Nim already requires you to be
@ -424,4 +424,3 @@ leaks by calling
.. code-block:: nim .. code-block:: nim
system.tearDownForeignThreadGc() system.tearDownForeignThreadGc()

View file

@ -25,7 +25,7 @@ move semantics and destructors work in Nim.
Motivating example Motivating example
================== ==================
With the language mechanisms described here a custom seq could be With the language mechanisms described here, a custom seq could be
written as: written as:
.. code-block:: nim .. code-block:: nim
@ -88,7 +88,7 @@ Lifetime-tracking hooks
======================= =======================
The memory management for Nim's standard ``string`` and ``seq`` types as The memory management for Nim's standard ``string`` and ``seq`` types as
well as other standard collections is performed via so called well as other standard collections is performed via so-called
"Lifetime-tracking hooks" or "type-bound operators". There are 3 different "Lifetime-tracking hooks" or "type-bound operators". There are 3 different
hooks for each (generic or concrete) object type ``T`` (``T`` can also be a hooks for each (generic or concrete) object type ``T`` (``T`` can also be a
``distinct`` type) that are called implicitly by the compiler. ``distinct`` type) that are called implicitly by the compiler.
@ -128,13 +128,13 @@ The general pattern in ``=destroy`` looks like:
------------ ------------
A `=sink` hook moves an object around, the resources are stolen from the source A `=sink` hook moves an object around, the resources are stolen from the source
and passed to the destination. It is ensured that source's destructor does and passed to the destination. It is ensured that the source's destructor does
not free the resources afterwards by setting the object to its default value not free the resources afterward by setting the object to its default value
(the value the object's state started in). Setting an object ``x`` back to its (the value the object's state started in). Setting an object ``x`` back to its
default value is written as ``wasMoved(x)``. When not provided the compiler default value is written as ``wasMoved(x)``. When not provided the compiler
is using a combination of `=destroy` and `copyMem` instead. This is efficient is using a combination of `=destroy` and `copyMem` instead. This is efficient
hence users rarely need to implement their own `=sink` operator, it is enough to hence users rarely need to implement their own `=sink` operator, it is enough to
provide `=destroy` and `=copy`, compiler will take care about the rest. provide `=destroy` and `=copy`, compiler will take care of the rest.
The prototype of this hook for a type ``T`` needs to be: The prototype of this hook for a type ``T`` needs to be:
@ -191,7 +191,7 @@ Move semantics
============== ==============
A "move" can be regarded as an optimized copy operation. If the source of the A "move" can be regarded as an optimized copy operation. If the source of the
copy operation is not used afterwards, the copy can be replaced by a move. This copy operation is not used afterward, the copy can be replaced by a move. This
document uses the notation ``lastReadOf(x)`` to describe that ``x`` is not document uses the notation ``lastReadOf(x)`` to describe that ``x`` is not
used afterwards. This property is computed by a static control flow analysis used afterwards. This property is computed by a static control flow analysis
but can also be enforced by using ``system.move`` explicitly. but can also be enforced by using ``system.move`` explicitly.
@ -218,7 +218,7 @@ Sink parameters
=============== ===============
To move a variable into a collection usually ``sink`` parameters are involved. To move a variable into a collection usually ``sink`` parameters are involved.
A location that is passed to a ``sink`` parameter should not be used afterwards. A location that is passed to a ``sink`` parameter should not be used afterward.
This is ensured by a static analysis over a control flow graph. If it cannot be This is ensured by a static analysis over a control flow graph. If it cannot be
proven to be the last usage of the location, a copy is done instead and this proven to be the last usage of the location, a copy is done instead and this
copy is then passed to the sink parameter. copy is then passed to the sink parameter.
@ -232,7 +232,7 @@ without any further overloads and ``put`` might not take ownership of ``k`` if
not a linear type system. not a linear type system.
The employed static analysis is limited and only concerned with local variables; The employed static analysis is limited and only concerned with local variables;
however object and tuple fields are treated as separate entities: however, object and tuple fields are treated as separate entities:
.. code-block:: nim .. code-block:: nim
@ -509,7 +509,7 @@ to avoid this overhead:
In fact, ``.cursor`` more generally prevents object construction/destruction pairs In fact, ``.cursor`` more generally prevents object construction/destruction pairs
and so can also be useful in other contexts. The alternative solution would be to and so can also be useful in other contexts. The alternative solution would be to
use raw pointers (``ptr``) instead which is more cumbersome and also more dangerous use raw pointers (``ptr``) instead which is more cumbersome and also more dangerous
for Nim's evolution: Later on the compiler can try to prove ``.cursor`` annotations for Nim's evolution: Later on, the compiler can try to prove ``.cursor`` annotations
to be safe, but for ``ptr`` the compiler has to remain silent about possible to be safe, but for ``ptr`` the compiler has to remain silent about possible
problems. problems.
@ -522,7 +522,7 @@ a form of copy elision.
To see how and when we can do that, think about this question: In `dest = src` when To see how and when we can do that, think about this question: In `dest = src` when
do we really have to *materialize* the full copy? - Only if `dest` or `src` are mutated do we really have to *materialize* the full copy? - Only if `dest` or `src` are mutated
afterwards. If `dest` is a local variable that is simple to analyse. And if `src` is a afterward. If `dest` is a local variable that is simple to analyze. And if `src` is a
location derived from a formal parameter, we also know it is not mutated! In other location derived from a formal parameter, we also know it is not mutated! In other
words, we do a compile-time copy-on-write analysis. words, we do a compile-time copy-on-write analysis.
@ -547,7 +547,7 @@ other words, a copy ``x = y`` is implemented
as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``. as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``.
Other value-based compound types like ``object`` and ``array`` are handled Other value-based compound types like ``object`` and ``array`` are handled
correspondingly. For ``object`` however, the compiler generated hooks correspondingly. For ``object`` however, the compiler-generated hooks
can be overridden. This can also be important to use an alternative traversal can be overridden. This can also be important to use an alternative traversal
of the involved data structure that is more efficient or in order to avoid of the involved data structure that is more efficient or in order to avoid
deep recursions. deep recursions.

View file

@ -14,7 +14,7 @@ Introduction
This document describes the `documentation generation tools`:idx: built into This document describes the `documentation generation tools`:idx: built into
the `Nim compiler <nimc.html>`_, which can generate HTML and JSON output the `Nim compiler <nimc.html>`_, which can generate HTML and JSON output
from input .nim files and projects, as well as HTML and LaTeX from input RST from input .nim files and projects, as well as HTML and LaTeX from input RST
(reStructuredText) files. The output documentation will include module (reStructuredText) files. The output documentation will include the module
dependencies (``import``), any top-level documentation comments (##), and dependencies (``import``), any top-level documentation comments (##), and
exported symbols (*), including procedures, types, and variables. exported symbols (*), including procedures, types, and variables.
@ -107,7 +107,7 @@ Document Types
HTML HTML
---- ----
Generation of HTML documents is done via the ``doc`` command. This command The generation of HTML documents is done via the ``doc`` command. This command
takes either a single .nim file, outputting a single .html file with the same takes either a single .nim file, outputting a single .html file with the same
base filename, or multiple .nim files, outputting multiple .html files and, base filename, or multiple .nim files, outputting multiple .html files and,
optionally, an index file. optionally, an index file.
@ -121,15 +121,15 @@ Partial Output::
... ...
The full output can be seen here: `docgen_sample.html <docgen_sample.html>`_. The full output can be seen here: `docgen_sample.html <docgen_sample.html>`_.
It runs after semantic checking, and includes pragmas attached implicitly by the It runs after semantic checking and includes pragmas attached implicitly by the
compiler. compiler.
JSON JSON
---- ----
Generation of JSON documents is done via the ``jsondoc`` command. This command The generation of JSON documents is done via the ``jsondoc`` command. This command
takes in a .nim file, and outputs a .json file with the same base filename. Note takes in a .nim file and outputs a .json file with the same base filename. Note
that this tool is built off of the ``doc`` command (previously ``doc2``), and that this tool is built off of the ``doc`` command (previously ``doc2``), and
contains the same information. contains the same information.
@ -153,8 +153,8 @@ Output::
] ]
} }
Similarly to the old ``doc`` command the old ``jsondoc`` command has been Similarly to the old ``doc`` command, the old ``jsondoc`` command has been
renamed ``jsondoc0``. renamed to ``jsondoc0``.
The ``jsondoc0`` command:: The ``jsondoc0`` command::
nim jsondoc0 sample nim jsondoc0 sample
@ -197,8 +197,8 @@ Index switch
This will generate an index of all the exported symbols in the input Nim This will generate an index of all the exported symbols in the input Nim
module, and put it into a neighboring file with the extension of ``.idx``. The module, and put it into a neighboring file with the extension of ``.idx``. The
index file is line oriented (newlines have to be escaped). Each line index file is line-oriented (newlines have to be escaped). Each line
represents a tab separated record of several columns, the first two mandatory, represents a tab-separated record of several columns, the first two mandatory,
the rest optional. See the `Index (idx) file format`_ section for details. the rest optional. See the `Index (idx) file format`_ section for details.
Once index files have been generated for one or more modules, the Nim Once index files have been generated for one or more modules, the Nim
@ -231,7 +231,7 @@ You can edit ``config/nimdoc.cfg`` and modify the ``doc.item.seesrc`` value with
In the case of Nim's own documentation, the ``commit`` value is just a commit In the case of Nim's own documentation, the ``commit`` value is just a commit
hash to append to a formatted URL to https://github.com/nim-lang/Nim. The hash to append to a formatted URL to https://github.com/nim-lang/Nim. The
``tools/nimweb.nim`` helper queries the current git commit hash during doc ``tools/nimweb.nim`` helper queries the current git commit hash during the doc
generation, but since you might be working on an unpublished repository, it generation, but since you might be working on an unpublished repository, it
also allows specifying a ``githash`` value in ``web/website.ini`` to force a also allows specifying a ``githash`` value in ``web/website.ini`` to force a
specific commit in the output. specific commit in the output.
@ -260,8 +260,8 @@ HTML anchor generation
====================== ======================
When you run the ``rst2html`` command, all sections in the RST document will When you run the ``rst2html`` command, all sections in the RST document will
get an anchor you can hyperlink to. Usually you can guess the anchor lower get an anchor you can hyperlink to. Usually, you can guess the anchor lower
casing the section title and replacing spaces with dashes, and in any case you casing the section title and replacing spaces with dashes, and in any case, you
can get it from the table of contents. But when you run the ``doc`` or ``doc2`` can get it from the table of contents. But when you run the ``doc`` or ``doc2``
commands to generate API documentation, some symbol get one or two anchors at commands to generate API documentation, some symbol get one or two anchors at
the same time: a numerical identifier, or a plain name plus a complex name. the same time: a numerical identifier, or a plain name plus a complex name.
@ -274,20 +274,20 @@ numbers may shuffle around.
The plain name of a symbol is a simplified version of its fully exported The plain name of a symbol is a simplified version of its fully exported
signature. Variables or constants have the same plain name symbol as their signature. Variables or constants have the same plain name symbol as their
complex name. The plain name for procs, templates, and other callable types complex name. The plain name for procs, templates, and other callable types
will be their unquoted value after removing parameters, return types and will be their unquoted value after removing parameters, return types, and
pragmas. The plain name allows short and nice linking of symbols which works pragmas. The plain name allows short and nice linking of symbols that works
unless you have a module with collisions due to overloading. unless you have a module with collisions due to overloading.
If you hyperlink a plain name symbol and there are other matches on the same If you hyperlink a plain name symbol and there are other matches on the same
HTML file, most browsers will go to the first one. To differentiate the rest, HTML file, most browsers will go to the first one. To differentiate the rest,
you will need to use the complex name. A complex name for a callable type is you will need to use the complex name. A complex name for a callable type is
made up from several parts: made up of several parts:
(**plain symbol**)(**.type**),(**first param**)?(**,param type**)\* (**plain symbol**)(**.type**),(**first param**)?(**,param type**)\*
The first thing to note is that all callable types have at least a comma, even The first thing to note is that all callable types have at least a comma, even
if they don't have any parameters. If there are parameters, they are if they don't have any parameters. If there are parameters, they are
represented by their types and will be comma separated. To the plain symbol a represented by their types and will be comma-separated. To the plain symbol a
suffix may be added depending on the type of the callable: suffix may be added depending on the type of the callable:
------------- -------------- ------------- --------------
@ -337,15 +337,15 @@ references so they can be later concatenated into a big index file with
`mergeIndexes() <rstgen.html#mergeIndexes,string>`_. This section documents `mergeIndexes() <rstgen.html#mergeIndexes,string>`_. This section documents
the file format in detail. the file format in detail.
Index files are line oriented and tab separated (newline and tab characters Index files are line-oriented and tab-separated (newline and tab characters
have to be escaped). Each line represents a record with at least two fields, have to be escaped). Each line represents a record with at least two fields
but can have up to four (additional columns are ignored). The content of these but can have up to four (additional columns are ignored). The content of these
columns is: columns is:
1. Mandatory term being indexed. Terms can include quoting according to 1. Mandatory term being indexed. Terms can include quoting according to
Nim's rules (e.g. \`^\`). Nim's rules (e.g. \`^\`).
2. Base filename plus anchor hyperlink (e.g. ``algorithm.html#*,int,SortOrder``). 2. Base filename plus anchor hyperlink (e.g. ``algorithm.html#*,int,SortOrder``).
3. Optional human readable string to display as hyperlink. If the value is not 3. Optional human-readable string to display as a hyperlink. If the value is not
present or is the empty string, the hyperlink will be rendered present or is the empty string, the hyperlink will be rendered
using the term. Prefix whitespace indicates that this entry is using the term. Prefix whitespace indicates that this entry is
not for an API symbol but for a TOC entry. not for an API symbol but for a TOC entry.
@ -361,14 +361,14 @@ human reading.
To differentiate both types (documents and APIs), the index generator will add To differentiate both types (documents and APIs), the index generator will add
to the index of documents an entry with the title of the document. Since the to the index of documents an entry with the title of the document. Since the
title is the topmost element, it will be added with a second field containing title is the topmost element, it will be added with a second field containing
just the filename without any HTML anchor. By convention this entry without just the filename without any HTML anchor. By convention, this entry without
anchor is the *title entry*, and since entries in the index file are added as anchor is the *title entry*, and since entries in the index file are added as
they are scanned, the title entry will be the first line. The title for APIs they are scanned, the title entry will be the first line. The title for APIs
is not present because it can be generated concatenating the name of the file is not present because it can be generated concatenating the name of the file
to the word **Module**. to the word **Module**.
Normal symbols are added to the index with surrounding whitespaces removed. An Normal symbols are added to the index with surrounding whitespaces removed. An
exception to this are table of content (TOC) entries. TOC entries are added to exception to this are the table of content (TOC) entries. TOC entries are added to
the index file with their third column having as much prefix spaces as their the index file with their third column having as much prefix spaces as their
level is in the TOC (at least 1 character). The prefix whitespace helps to level is in the TOC (at least 1 character). The prefix whitespace helps to
filter TOC entries from API or text symbols. This is important because the filter TOC entries from API or text symbols. This is important because the
@ -379,14 +379,14 @@ final index, and TOC entries found in ``.nim`` files are discarded.
Additional resources Additional resources
==================== ====================
`Nim Compiler User Guide <nimc.html#compiler-usage-command-line-switches>`_ `Nim Compiler User Guide <nimc.html#compiler-usage-commandminusline-switches>`_
`RST Quick Reference `RST Quick Reference
<http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_ <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and
``config/nimdoc.tex.cfg`` configuration files. You can add and modify these ``config/nimdoc.tex.cfg`` configuration files. You can add and modify these
files to your project to change the look of docgen output. files to your project to change the look of the docgen output.
You can import the `packages/docutils/rstgen module <rstgen.html>`_ in your You can import the `packages/docutils/rstgen module <rstgen.html>`_ in your
programs if you want to reuse the compiler's documentation generation procs. programs if you want to reuse the compiler's documentation generation procs.

View file

@ -13,8 +13,8 @@ Introduction
This document describes the usage of the *DrNim* tool. DrNim combines This document describes the usage of the *DrNim* tool. DrNim combines
the Nim frontend with the `Z3 <https://github.com/Z3Prover/z3>`_ proof the Nim frontend with the `Z3 <https://github.com/Z3Prover/z3>`_ proof
engine in order to allow verify / validate software written in Nim. engine, in order to allow verify/validate software written in Nim.
DrNim's command line options are the same as the Nim compiler's. DrNim's command-line options are the same as the Nim compiler's.
DrNim currently only checks the sections of your code that are marked DrNim currently only checks the sections of your code that are marked
@ -140,8 +140,8 @@ Example: insertionSort
swap a[t], a[t-1] swap a[t], a[t-1]
dec t dec t
Unfortunately the invariants required to prove this code correct take more Unfortunately, the invariants required to prove that this code is correct take more
code than the imperative instructions. However this effort can be compensated code than the imperative instructions. However, this effort can be compensated
by the fact that the result needs very little testing. Be aware though that by the fact that the result needs very little testing. Be aware though that
DrNim only proves that after ``insertionSort`` this condition holds:: DrNim only proves that after ``insertionSort`` this condition holds::

View file

@ -14,11 +14,11 @@ preserved.
Basic workflow Basic workflow
============== ==============
Currently hot code reloading does not work for the main module itself, Currently, hot code reloading does not work for the main module itself,
so we have to use a helper module where the major logic we want to change so we have to use a helper module where the major logic we want to change
during development resides. during development resides.
In this example we use SDL2 to create a window and we reload the logic In this example, we use SDL2 to create a window and we reload the logic
code when ``F9`` is pressed. The important lines are marked with ``#***``. code when ``F9`` is pressed. The important lines are marked with ``#***``.
To install SDL2 you can use ``nimble install sdl2``. To install SDL2 you can use ``nimble install sdl2``.
@ -125,7 +125,7 @@ Then recompile the project, but do not restart or quit the mymain.exe program!
nim c --hotcodereloading:on mymain.nim nim c --hotcodereloading:on mymain.nim
Now give the ``mymain`` SDL window the focus, press F9 and watch the Now give the ``mymain`` SDL window the focus, press F9, and watch the
updated version of the program. updated version of the program.

View file

@ -75,8 +75,8 @@ from rst to HTML. It also repeats the same operation but places the result in
the ``web/upload`` which can be used to update the website at the ``web/upload`` which can be used to update the website at
https://nim-lang.org. https://nim-lang.org.
By default the documentation will be built in parallel using the number of By default, the documentation will be built in parallel using the number of
available CPU cores. If any documentation build sub commands fail, they will available CPU cores. If any documentation build sub-commands fail, they will
be rerun in serial fashion so that meaningful error output can be gathered for be rerun in serial fashion so that meaningful error output can be gathered for
inspection. The ``--parallelBuild:n`` switch or configuration option can be inspection. The ``--parallelBuild:n`` switch or configuration option can be
used to force a specific number of parallel jobs or run everything serially used to force a specific number of parallel jobs or run everything serially

View file

@ -7,7 +7,7 @@ Nim Standard Library
.. contents:: .. contents::
Nim's library is divided into *pure libraries*, *impure libraries* and *wrappers*. Nim's library is divided into *pure libraries*, *impure libraries*, and *wrappers*.
Pure libraries do not depend on any external ``*.dll`` or ``lib*.so`` binary Pure libraries do not depend on any external ``*.dll`` or ``lib*.so`` binary
while impure libraries do. A wrapper is an impure library that is a very while impure libraries do. A wrapper is an impure library that is a very
@ -48,7 +48,7 @@ Core
---- ----
* `bitops <bitops.html>`_ * `bitops <bitops.html>`_
Provides a series of low level methods for bit manipulation. Provides a series of low-level methods for bit manipulation.
* `cpuinfo <cpuinfo.html>`_ * `cpuinfo <cpuinfo.html>`_
This module implements procs to determine the number of CPUs / cores. This module implements procs to determine the number of CPUs / cores.
@ -69,7 +69,7 @@ Core
Reentrant locks for Nim. Reentrant locks for Nim.
* `typeinfo <typeinfo.html>`_ * `typeinfo <typeinfo.html>`_
Provides (unsafe) access to Nim's run time type information. Provides (unsafe) access to Nim's run-time type information.
* `typetraits <typetraits.html>`_ * `typetraits <typetraits.html>`_
This module defines compile-time reflection procs for working with types. This module defines compile-time reflection procs for working with types.
@ -83,7 +83,7 @@ Algorithms
---------- ----------
* `algorithm <algorithm.html>`_ * `algorithm <algorithm.html>`_
Implements some common generic algorithms like sort or binary search. This module implements some common generic algorithms like sort or binary search.
* `sequtils <sequtils.html>`_ * `sequtils <sequtils.html>`_
This module implements operations for the built-in seq type This module implements operations for the built-in seq type
@ -96,7 +96,7 @@ Collections
* `critbits <critbits.html>`_ * `critbits <critbits.html>`_
This module implements a *crit bit tree* which is an efficient This module implements a *crit bit tree* which is an efficient
container for a sorted set of strings, or for a sorted mapping of strings. container for a sorted set of strings, or a sorted mapping of strings.
* `deques <deques.html>`_ * `deques <deques.html>`_
Implementation of a double-ended queue. Implementation of a double-ended queue.
@ -119,13 +119,13 @@ Collections
Nim hash and bit set support. Nim hash and bit set support.
* `sharedlist <sharedlist.html>`_ * `sharedlist <sharedlist.html>`_
Nim shared linked list support. Contains shared singly linked list. Nim shared linked list support. Contains a shared singly-linked list.
* `sharedtables <sharedtables.html>`_ * `sharedtables <sharedtables.html>`_
Nim shared hash table support. Contains shared tables. Nim shared hash table support. Contains shared tables.
* `tables <tables.html>`_ * `tables <tables.html>`_
Nim hash table support. Contains tables, ordered tables and count tables. Nim hash table support. Contains tables, ordered tables, and count tables.
@ -154,8 +154,8 @@ String handling
* `ropes <ropes.html>`_ * `ropes <ropes.html>`_
This module contains support for a *rope* data type. This module contains support for a *rope* data type.
Ropes can represent very long strings efficiently; especially concatenation Ropes can represent very long strings efficiently;
is done in O(1) instead of O(n). especially concatenation is done in O(1) instead of O(n).
* `strformat <strformat.html>`_ * `strformat <strformat.html>`_
Macro based standard string interpolation/formatting. Inspired by Macro based standard string interpolation/formatting. Inspired by
@ -207,7 +207,7 @@ Generic Operating System Services
and the OS's native package manager. and the OS's native package manager.
Its primary purpose is to produce output for Nimble packages, Its primary purpose is to produce output for Nimble packages,
but it also contains the widely used **Distribution** enum but it also contains the widely used **Distribution** enum
that is useful for writing platform specific code. that is useful for writing platform-specific code.
See `packaging <packaging.html>`_ for hints on distributing Nim using OS packages. See `packaging <packaging.html>`_ for hints on distributing Nim using OS packages.
* `dynlib <dynlib.html>`_ * `dynlib <dynlib.html>`_
@ -218,7 +218,7 @@ Generic Operating System Services
data structures. data structures.
* `memfiles <memfiles.html>`_ * `memfiles <memfiles.html>`_
This module provides support for memory mapped files (Posix's ``mmap``) This module provides support for memory-mapped files (Posix's ``mmap``)
on the different operating systems. on the different operating systems.
* `os <os.html>`_ * `os <os.html>`_
@ -245,7 +245,7 @@ Math libraries
-------------- --------------
* `complex <complex.html>`_ * `complex <complex.html>`_
This module implements complex numbers and their mathematical operations. This module implements complex numbers and relevant mathematical operations.
* `fenv <fenv.html>`_ * `fenv <fenv.html>`_
Floating-point environment. Handling of floating-point rounding and Floating-point environment. Handling of floating-point rounding and
@ -261,7 +261,7 @@ Math libraries
Fast and tiny random number generator. Fast and tiny random number generator.
* `rationals <rationals.html>`_ * `rationals <rationals.html>`_
This module implements rational numbers and their mathematical operations. This module implements rational numbers and relevant mathematical operations.
* `stats <stats.html>`_ * `stats <stats.html>`_
Statistical analysis Statistical analysis
@ -317,10 +317,10 @@ Internet Protocols and Support
* `selectors <selectors.html>`_ * `selectors <selectors.html>`_
This module implements a selector API with backends specific to each OS. This module implements a selector API with backends specific to each OS.
Currently epoll on Linux and select on other operating systems. Currently, epoll on Linux and select on other operating systems.
* `smtp <smtp.html>`_ * `smtp <smtp.html>`_
This module implement a simple SMTP client. This module implements a simple SMTP client.
* `uri <uri.html>`_ * `uri <uri.html>`_
This module provides functions for working with URIs. This module provides functions for working with URIs.
@ -340,47 +340,46 @@ Parsers
This module parses an HTML document and creates its XML tree representation. This module parses an HTML document and creates its XML tree representation.
* `json <json.html>`_ * `json <json.html>`_
High performance JSON parser. High-performance JSON parser.
* `lexbase <lexbase.html>`_ * `lexbase <lexbase.html>`_
This is a low level module that implements an extremely efficient buffering This is a low-level module that implements an extremely efficient buffering
scheme for lexers and parsers. This is used by the diverse parsing modules. scheme for lexers and parsers. This is used by the diverse parsing modules.
* `parsecfg <parsecfg.html>`_ * `parsecfg <parsecfg.html>`_
The ``parsecfg`` module implements a high performance configuration file The ``parsecfg`` module implements a high-performance configuration file
parser. The configuration file's syntax is similar to the Windows ``.ini`` parser. The configuration file's syntax is similar to the Windows ``.ini``
format, but much more powerful, as it is not a line based parser. String format, but much more powerful, as it is not a line based parser. String
literals, raw string literals and triple quote string literals are supported literals, raw string literals, and triple quote string literals are supported
as in the Nim programming language. as in the Nim programming language.
* `parsecsv <parsecsv.html>`_ * `parsecsv <parsecsv.html>`_
The ``parsecsv`` module implements a simple high performance CSV parser. The ``parsecsv`` module implements a simple high-performance CSV parser.
* `parseopt <parseopt.html>`_ * `parseopt <parseopt.html>`_
The ``parseopt`` module implements a command line option parser. The ``parseopt`` module implements a command line option parser.
* `parsesql <parsesql.html>`_ * `parsesql <parsesql.html>`_
The ``parsesql`` module implements a simple high performance SQL parser. The ``parsesql`` module implements a simple high-performance SQL parser.
* `parsexml <parsexml.html>`_ * `parsexml <parsexml.html>`_
The ``parsexml`` module implements a simple high performance XML/HTML parser. The ``parsexml`` module implements a simple high performance XML/HTML parser.
The only encoding that is supported is UTF-8. The parser has been designed The only encoding that is supported is UTF-8. The parser has been designed
to be somewhat error correcting, so that even some "wild HTML" found on the to be somewhat error-correcting, so that even some "wild HTML" found on the
Web can be parsed with it. web can be parsed with it.
Docutils Docutils
-------- --------
* `packages/docutils/highlite <highlite.html>`_ * `packages/docutils/highlite <highlite.html>`_
Source highlighter for programming or markup languages. Currently Source highlighter for programming or markup languages. Currently,
only few languages are supported, other languages may be added. only a few languages are supported, other languages may be added.
The interface supports one language nested in another. The interface supports one language nested in another.
* `packages/docutils/rst <rst.html>`_ * `packages/docutils/rst <rst.html>`_
This module implements a reStructuredText parser. A large subset This module implements a reStructuredText parser. A large subset
is implemented. Some features of the markdown wiki syntax are is implemented. Some features of the markdown wiki syntax are also supported.
also supported.
* `packages/docutils/rstast <rstast.html>`_ * `packages/docutils/rstast <rstast.html>`_
This module implements an AST for the reStructuredText parser. This module implements an AST for the reStructuredText parser.
@ -425,7 +424,7 @@ Hashing
* `oids <oids.html>`_ * `oids <oids.html>`_
An OID is a global ID that consists of a timestamp, An OID is a global ID that consists of a timestamp,
a unique counter and a random value. This combination should suffice to a unique counter, and a random value. This combination should suffice to
produce a globally distributed unique ID. This implementation was extracted produce a globally distributed unique ID. This implementation was extracted
from the Mongodb interface and it thus binary compatible with a Mongo OID. from the Mongodb interface and it thus binary compatible with a Mongo OID.
@ -460,7 +459,7 @@ Miscellaneous
Implements a Unit testing DSL. Implements a Unit testing DSL.
* `std/varints <varints.html>`_ * `std/varints <varints.html>`_
Decode variable length integers that are compatible with SQLite. Decode variable-length integers that are compatible with SQLite.
Modules for JS backend Modules for JS backend
@ -476,7 +475,7 @@ Modules for JS backend
Wrapper for the ``console`` object. Wrapper for the ``console`` object.
* `jscore <jscore.html>`_ * `jscore <jscore.html>`_
Wrapper of core JavaScript functions. For most purposes you should be using The wrapper of core JavaScript functions. For most purposes, you should be using
the ``math``, ``json``, and ``times`` stdlib modules instead of this module. the ``math``, ``json``, and ``times`` stdlib modules instead of this module.
* `jsffi <jsffi.html>`_ * `jsffi <jsffi.html>`_
@ -517,7 +516,7 @@ The generated HTML for some of these wrappers is so huge that it is
not contained in the distribution. You can then find them on the website. not contained in the distribution. You can then find them on the website.
Windows specific Windows-specific
---------------- ----------------
* `winlean <winlean.html>`_ * `winlean <winlean.html>`_
@ -545,7 +544,7 @@ GUI libraries
------------- -------------
* `iup <iup.html>`_ * `iup <iup.html>`_
Wrapper of the IUP GUI library. The wrapper of the IUP GUI library.
Database support Database support

File diff suppressed because it is too large Load diff

View file

@ -26,9 +26,9 @@ Nim is free software; it is licensed under the
Compiler Usage Compiler Usage
============== ==============
Command line switches Command-line switches
--------------------- ---------------------
Basic command line switches are: Basic command-line switches are:
Usage: Usage:
@ -36,7 +36,7 @@ Usage:
---- ----
Advanced command line switches are: Advanced command-line switches are:
.. include:: advopt.txt .. include:: advopt.txt
@ -62,7 +62,7 @@ SmallLshouldNotBeUsed The letter 'l' should not be used as an
identifier. identifier.
EachIdentIsTuple The code contains a confusing ``var`` EachIdentIsTuple The code contains a confusing ``var``
declaration. declaration.
User Some user defined warning. User Some user-defined warning.
========================== ============================================ ========================== ============================================
@ -118,7 +118,7 @@ Level Description
<manual.html#implementation-specific-pragmas-compile-pragma>`_. <manual.html#implementation-specific-pragmas-compile-pragma>`_.
This is the default level. This is the default level.
2 Displays compilation statistics, enumerates the dynamic 2 Displays compilation statistics, enumerates the dynamic
libraries that will be loaded by the final binary and dumps to libraries that will be loaded by the final binary, and dumps to
standard output the result of applying `a filter to the source code standard output the result of applying `a filter to the source code
<filters.html>`_ if any filter was used during compilation. <filters.html>`_ if any filter was used during compilation.
3 In addition to the previous levels dumps a debug stack trace 3 In addition to the previous levels dumps a debug stack trace
@ -126,10 +126,10 @@ Level Description
===== ============================================ ===== ============================================
Compile time symbols Compile-time symbols
-------------------- --------------------
Through the ``-d:x`` or ``--define:x`` switch you can define compile time Through the ``-d:x`` or ``--define:x`` switch you can define compile-time
symbols for conditional compilation. The defined switches can be checked in symbols for conditional compilation. The defined switches can be checked in
source code with the `when statement source code with the `when statement
<manual.html#statements-and-expressions-when-statement>`_ and <manual.html#statements-and-expressions-when-statement>`_ and
@ -139,14 +139,14 @@ enabled for better performance. Another common use is the ``-d:ssl`` switch to
activate SSL sockets. activate SSL sockets.
Additionally, you may pass a value along with the symbol: ``-d:x=y`` Additionally, you may pass a value along with the symbol: ``-d:x=y``
which may be used in conjunction with the `compile time define which may be used in conjunction with the `compile-time define
pragmas<manual.html#implementation-specific-pragmas-compile-time-define-pragmas>`_ pragmas<manual.html#implementation-specific-pragmas-compileminustime-define-pragmas>`_
to override symbols during build time. to override symbols during build time.
Compile time symbols are completely **case insensitive** and underscores are Compile-time symbols are completely **case insensitive** and underscores are
ignored too. ``--define:FOO`` and ``--define:foo`` are identical. ignored too. ``--define:FOO`` and ``--define:foo`` are identical.
Compile time symbols starting with the ``nim`` prefix are reserved for the Compile-time symbols starting with the ``nim`` prefix are reserved for the
implementation and should not be used elsewhere. implementation and should not be used elsewhere.
@ -154,7 +154,7 @@ Configuration files
------------------- -------------------
**Note:** The *project file name* is the name of the ``.nim`` file that is **Note:** The *project file name* is the name of the ``.nim`` file that is
passed as a command line argument to the compiler. passed as a command-line argument to the compiler.
The ``nim`` executable processes configuration files in the following The ``nim`` executable processes configuration files in the following
@ -162,12 +162,12 @@ directories (in this order; later files overwrite previous settings):
1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or ``<Nim's installation directory>\config\nim.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option. 1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or ``<Nim's installation directory>\config\nim.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option.
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. 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.
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. 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.
4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option. 4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command-line option.
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. 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.
Command line settings have priority over configuration file settings. Command-line settings have priority over configuration file settings.
The default build of a project is a `debug build`:idx:. To compile a The default build of a project is a `debug build`:idx:. To compile a
`release build`:idx: define the ``release`` symbol:: `release build`:idx: define the ``release`` symbol::
@ -217,12 +217,12 @@ The ``_r`` suffix is used for release builds, ``_d`` is for debug builds.
This makes it easy to delete all generated files. This makes it easy to delete all generated files.
The ``--nimcache`` The ``--nimcache``
`compiler switch <#compiler-usage-command-line-switches>`_ can be used to `compiler switch <#compiler-usage-commandminusline-switches>`_ can be used to
to change the ``nimcache`` directory. to change the ``nimcache`` directory.
However, the generated C code is not platform independent. C code generated for However, the generated C code is not platform-independent. C code generated for
Linux does not compile on Windows, for instance. The comment on top of the Linux does not compile on Windows, for instance. The comment on top of the
C file lists the OS, CPU and CC the file has been compiled for. C file lists the OS, CPU, and CC the file has been compiled for.
Compiler Selection Compiler Selection
@ -245,7 +245,7 @@ To use the ``CC`` environment variable, use ``nim c --cc:env myfile.nim``. To us
since Nim version 1.4. since Nim version 1.4.
Cross compilation Cross-compilation
================= =================
To cross compile, use for example:: To cross compile, use for example::
@ -268,10 +268,10 @@ configuration file should contain something like::
arm.linux.gcc.exe = "arm-linux-gcc" arm.linux.gcc.exe = "arm-linux-gcc"
arm.linux.gcc.linkerexe = "arm-linux-gcc" arm.linux.gcc.linkerexe = "arm-linux-gcc"
Cross compilation for Windows Cross-compilation for Windows
============================= =============================
To cross compile for Windows from Linux or macOS using the MinGW-w64 toolchain:: To cross-compile for Windows from Linux or macOS using the MinGW-w64 toolchain::
nim c -d:mingw myproject.nim nim c -d:mingw myproject.nim
@ -284,15 +284,15 @@ The MinGW-w64 toolchain can be installed as follows::
OSX: brew install mingw-w64 OSX: brew install mingw-w64
Cross compilation for Android Cross-compilation for Android
============================= =============================
There are two ways to compile for Android: terminal programs (Termux) and with There are two ways to compile for Android: terminal programs (Termux) and with
the NDK (Android Native Development Kit). the NDK (Android Native Development Kit).
First one is to treat Android as a simple Linux and use The first one is to treat Android as a simple Linux and use
`Termux <https://wiki.termux.com>`_ to connect and run the Nim compiler `Termux <https://wiki.termux.com>`_ to connect and run the Nim compiler
directly on android as if it was Linux. These programs are console only directly on android as if it was Linux. These programs are console-only
programs that can't be distributed in the Play Store. programs that can't be distributed in the Play Store.
Use regular ``nim c`` inside termux to make Android terminal programs. Use regular ``nim c`` inside termux to make Android terminal programs.
@ -300,8 +300,8 @@ Use regular ``nim c`` inside termux to make Android terminal programs.
Normal Android apps are written in Java, to use Nim inside an Android app Normal Android apps are written in Java, to use Nim inside an Android app
you need a small Java stub that calls out to a native library written in you need a small Java stub that calls out to a native library written in
Nim using the `NDK <https://developer.android.com/ndk>`_. You can also use Nim using the `NDK <https://developer.android.com/ndk>`_. You can also use
`native-acitivty <https://developer.android.com/ndk/samples/sample_na>`_ `native-activity <https://developer.android.com/ndk/samples/sample_na>`_
to have the Java stub be auto generated for you. to have the Java stub be auto-generated for you.
Use ``nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on`` to Use ``nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on`` to
generate the C source files you need to include in your Android Studio generate the C source files you need to include in your Android Studio
@ -323,10 +323,10 @@ of your program.
NimMain() # initialize garbage collector memory, types and stack NimMain() # initialize garbage collector memory, types and stack
Cross compilation for iOS Cross-compilation for iOS
========================= =========================
To cross compile for iOS you need to be on a MacOS computer and use XCode. To cross-compile for iOS you need to be on a macOS computer and use XCode.
Normal languages for iOS development are Swift and Objective C. Both of these Normal languages for iOS development are Swift and Objective C. Both of these
use LLVM and can be compiled into object files linked together with C, C++ use LLVM and can be compiled into object files linked together with C, C++
or Objective C code produced by Nim. or Objective C code produced by Nim.
@ -338,8 +338,8 @@ sign everything.
Because Nim is part of a library it can't have its own c style ``main()`` so you Because Nim is part of a library it can't have its own c style ``main()`` so you
would need to define `main` that calls ``autoreleasepool`` and would need to define `main` that calls ``autoreleasepool`` and
``UIApplicationMain`` to do it, or use a library like SDL2 or GLFM. After ``UIApplicationMain`` to do it, or use a library like SDL2 or GLFM. After
the iOS setup is done, it's very important to call ``NimMain()`` in order to the iOS setup is done, it's very important to call ``NimMain()`` to
initialize Nim's garbage collector and to run the top level statements initialize Nim's garbage collector and to run the top-level statements
of your program. of your program.
.. code-block:: Nim .. code-block:: Nim
@ -352,7 +352,7 @@ Note: XCode's "make clean" gets confused about the generated nim.c files,
so you need to clean those files manually to do a clean build. so you need to clean those files manually to do a clean build.
Cross compilation for Nintendo Switch Cross-compilation for Nintendo Switch
===================================== =====================================
Simply add --os:nintendoswitch Simply add --os:nintendoswitch
@ -374,7 +374,7 @@ The DevkitPro setup must be the same as the default with their new installer
`here for Mac/Linux <https://github.com/devkitPro/pacman/releases>`_ or `here for Mac/Linux <https://github.com/devkitPro/pacman/releases>`_ or
`here for Windows <https://github.com/devkitPro/installer/releases>`_. `here for Windows <https://github.com/devkitPro/installer/releases>`_.
For example, with the above mentioned config:: For example, with the above-mentioned config::
nim c --os:nintendoswitch switchhomebrew.nim nim c --os:nintendoswitch switchhomebrew.nim
@ -479,8 +479,7 @@ debugging with GDB.
StackTrace option StackTrace option
----------------- -----------------
If the ``stackTrace`` option is turned on, the generated C contains code to If the ``stackTrace`` option is turned on, the generated C contains code to
ensure that proper stack traces are given if the program crashes or an ensure that proper stack traces are given if the program crashes or some uncaught exception is raised.
uncaught exception is raised.
LineTrace option LineTrace option
@ -509,8 +508,8 @@ Backend language options
The typical compiler usage involves using the ``compile`` or ``c`` command to The typical compiler usage involves using the ``compile`` or ``c`` command to
transform a ``.nim`` file into one or more ``.c`` files which are then transform a ``.nim`` file into one or more ``.c`` files which are then
compiled with the platform's C compiler into a static binary. However there compiled with the platform's C compiler into a static binary. However, there
are other commands to compile to C++, Objective-C or JavaScript. More details are other commands to compile to C++, Objective-C, or JavaScript. More details
can be read in the `Nim Backend Integration document <backends.html>`_. can be read in the `Nim Backend Integration document <backends.html>`_.
@ -584,7 +583,7 @@ The ``--opt:size`` flag instructs Nim to optimize code generation for small
size (with the help of the C compiler), the ``flto`` flags enable link-time size (with the help of the C compiler), the ``flto`` flags enable link-time
optimization in the compiler and linker. optimization in the compiler and linker.
Check the `Cross compilation` section for instructions how to compile the Check the `Cross-compilation` section for instructions on how to compile the
program for your target. program for your target.
Nim for realtime systems Nim for realtime systems
@ -630,7 +629,7 @@ Optimizing string handling
String assignments are sometimes expensive in Nim: They are required to String assignments are sometimes expensive in Nim: They are required to
copy the whole string. However, the compiler is often smart enough to not copy copy the whole string. However, the compiler is often smart enough to not copy
strings. Due to the argument passing semantics, strings are never copied when strings. Due to the argument passing semantics, strings are never copied when
passed to subroutines. The compiler does not copy strings that are a result from passed to subroutines. The compiler does not copy strings that are a result of
a procedure call, because the callee returns a new string anyway. a procedure call, because the callee returns a new string anyway.
Thus it is efficient to do: Thus it is efficient to do:
@ -638,7 +637,7 @@ Thus it is efficient to do:
var s = procA() # assignment will not copy the string; procA allocates a new var s = procA() # assignment will not copy the string; procA allocates a new
# string already # string already
However it is not efficient to do: However, it is not efficient to do:
.. code-block:: Nim .. code-block:: Nim
var s = varA # assignment has to copy the whole string into a new buffer! var s = varA # assignment has to copy the whole string into a new buffer!
@ -649,12 +648,12 @@ For ``let`` symbols a copy is not always necessary:
let s = varA # may only copy a pointer if it safe to do so let s = varA # may only copy a pointer if it safe to do so
If you know what you're doing, you can also mark single string (or sequence) If you know what you're doing, you can also mark single-string (or sequence)
objects as `shallow`:idx:\: objects as `shallow`:idx:\:
.. code-block:: Nim .. code-block:: Nim
var s = "abc" var s = "abc"
shallow(s) # mark 's' as shallow string shallow(s) # mark 's' as a shallow string
var x = s # now might not copy the string! var x = s # now might not copy the string!
Usage of ``shallow`` is always safe once you know the string won't be modified Usage of ``shallow`` is always safe once you know the string won't be modified

View file

@ -59,7 +59,7 @@ Key description
``Description`` the project's description ``Description`` the project's description
``App`` the application's type: "Console" or "GUI". If ``App`` the application's type: "Console" or "GUI". If
"Console", niminst generates a special batch file "Console", niminst generates a special batch file
for Windows to open up the command line shell. for Windows to open up the command-line shell.
``License`` the filename of the application's license ``License`` the filename of the application's license
==================== ======================================================= ==================== =======================================================
@ -114,7 +114,7 @@ Listed files will be installed into the OS's native library directory
Windows section Windows section
--------------- ---------------
The ``windows`` section supports the ``files`` key for Windows specific files. The ``windows`` section supports the ``files`` key for Windows-specific files.
Listed files will be installed into the application installation directory Listed files will be installed into the application installation directory
(``$appdir``). (``$appdir``).
@ -149,7 +149,7 @@ Key description
==================== ======================================================= ==================== =======================================================
``InstallScript`` boolean flag whether an installation shell script ``InstallScript`` boolean flag whether an installation shell script
should be generated. Example: ``InstallScript: "Yes"`` should be generated. Example: ``InstallScript: "Yes"``
``UninstallScript`` boolean flag whether a deinstallation shell script ``UninstallScript`` boolean flag whether a de-installation shell script
should be generated. should be generated.
Example: ``UninstallScript: "Yes"`` Example: ``UninstallScript: "Yes"``
==================== ======================================================= ==================== =======================================================
@ -184,7 +184,7 @@ Key description
==================== ======================================================= ==================== =======================================================
Real world example Real-world example
================== ==================
The installers for the Nim compiler itself are generated by niminst. Have a The installers for the Nim compiler itself are generated by niminst. Have a

View file

@ -2,7 +2,7 @@ Testament is an advanced automatic unittests runner for Nim tests, is used for t
offers process isolation for your tests, it can generate statistics about test cases, offers process isolation for your tests, it can generate statistics about test cases,
supports multiple targets (C, C++, ObjectiveC, JavaScript, etc), supports multiple targets (C, C++, ObjectiveC, JavaScript, etc),
simulated `Dry-Runs <https://en.wikipedia.org/wiki/Dry_run_(testing)>`_, simulated `Dry-Runs <https://en.wikipedia.org/wiki/Dry_run_(testing)>`_,
has logging, can generate HTML reports, skip tests from a file and more, has logging, can generate HTML reports, skip tests from a file, and more,
so can be useful to run your tests, even the most complex ones. so can be useful to run your tests, even the most complex ones.
@ -115,9 +115,9 @@ Example "template" **to edit** and write a Testament unittest:
* As you can see the "Spec" is just a ``discard """ """``. * As you can see the "Spec" is just a ``discard """ """``.
* Spec has sane defaults, so you dont need to provide them all, any simple assert will work Ok. * Spec has sane defaults, so you don't need to provide them all, any simple assert will work just fine.
* `This is not the full spec of Testament, check the Testament Spec on GitHub, see parseSpec(). <https://github.com/nim-lang/Nim/blob/devel/testament/specs.nim#L238>`_ * `This is not the full spec of Testament, check the Testament Spec on GitHub, see parseSpec(). <https://github.com/nim-lang/Nim/blob/devel/testament/specs.nim#L238>`_
* `Nim itself uses Testament, so theres plenty of test examples. <https://github.com/nim-lang/Nim/tree/devel/tests>`_ * `Nim itself uses Testament, so there are plenty of test examples. <https://github.com/nim-lang/Nim/tree/devel/tests>`_
* Has some built-in CI compatibility, like Azure Pipelines, etc. * Has some built-in CI compatibility, like Azure Pipelines, etc.
* `Testament supports inlined error messages on Unittests, basically comments with the expected error directly on the code. <https://github.com/nim-lang/Nim/blob/9a110047cbe2826b1d4afe63e3a1f5a08422b73f/tests/effects/teffects1.nim>`_ * `Testament supports inlined error messages on Unittests, basically comments with the expected error directly on the code. <https://github.com/nim-lang/Nim/blob/9a110047cbe2826b1d4afe63e3a1f5a08422b73f/tests/effects/teffects1.nim>`_
@ -172,7 +172,7 @@ JavaScript tests:
import jsconsole import jsconsole
console.log("My Frontend Project") console.log("My Frontend Project")
Compile time tests: Compile-time tests:
.. code-block:: nim .. code-block:: nim

View file

@ -14,7 +14,7 @@ The standard distribution ships with the following tools:
- | `Nimsuggest for IDE support <nimsuggest.html>`_ - | `Nimsuggest for IDE support <nimsuggest.html>`_
| Through the ``nimsuggest`` tool, any IDE can query a ``.nim`` source file | Through the ``nimsuggest`` tool, any IDE can query a ``.nim`` source file
and obtain useful information like definition of symbols or suggestions for and obtain useful information like the definition of symbols or suggestions for
completion. completion.
- | `C2nim <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ - | `C2nim <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_
@ -35,5 +35,5 @@ The standard distribution ships with the following tools:
is used for the development of Nim itself, offers process isolation for your tests, is used for the development of Nim itself, offers process isolation for your tests,
it can generate statistics about test cases, supports multiple targets (C, JS, etc), it can generate statistics about test cases, supports multiple targets (C, JS, etc),
`simulated Dry-Runs <https://en.wikipedia.org/wiki/Dry_run_(testing)>`_, `simulated Dry-Runs <https://en.wikipedia.org/wiki/Dry_run_(testing)>`_,
has logging, can generate HTML reports, skip tests from a file and more, has logging, can generate HTML reports, skip tests from a file, and more,
so can be useful to run your tests, even the most complex ones. so can be useful to run your tests, even the most complex ones.

View file

@ -18,7 +18,7 @@ Introduction
This document is a tutorial for the programming language *Nim*. This document is a tutorial for the programming language *Nim*.
This tutorial assumes that you are familiar with basic programming concepts This tutorial assumes that you are familiar with basic programming concepts
like variables, types or statements but is kept very basic. The `manual like variables, types, or statements but is kept very basic. The `manual
<manual.html>`_ contains many more examples of the advanced language features. <manual.html>`_ contains many more examples of the advanced language features.
All code examples in this tutorial, as well as the ones found in the rest of All code examples in this tutorial, as well as the ones found in the rest of
Nim's documentation, follow the `Nim style guide <nep1.html>`_. Nim's documentation, follow the `Nim style guide <nep1.html>`_.
@ -41,9 +41,9 @@ Save this code to the file "greetings.nim". Now compile and run it::
nim compile --run greetings.nim nim compile --run greetings.nim
With the ``--run`` `switch <nimc.html#compiler-usage-command-line-switches>`_ Nim With the ``--run`` `switch <nimc.html#compiler-usage-commandminusline-switches>`_ Nim
executes the file automatically after compilation. You can give your program executes the file automatically after compilation. You can give your program
command line arguments by appending them after the filename:: command-line arguments by appending them after the filename::
nim compile --run greetings.nim arg1 arg2 nim compile --run greetings.nim arg1 arg2
@ -55,17 +55,17 @@ To compile a release version use::
nim c -d:release greetings.nim nim c -d:release greetings.nim
By default the Nim compiler generates a large amount of runtime checks By default, the Nim compiler generates a large number of runtime checks
aiming for your debugging pleasure. With ``-d:release`` some checks are aiming for your debugging pleasure. With ``-d:release`` some checks are
`turned off and optimizations are turned on `turned off and optimizations are turned on
<nimc.html#compiler-usage-compile-time-symbols>`_. <nimc.html#compiler-usage-compileminustime-symbols>`_.
Though it should be pretty obvious what the program does, I will explain the Though it should be pretty obvious what the program does, I will explain the
syntax: statements which are not indented are executed when the program syntax: statements which are not indented are executed when the program
starts. Indentation is Nim's way of grouping statements. Indentation is starts. Indentation is Nim's way of grouping statements. Indentation is
done with spaces only, tabulators are not allowed. done with spaces only, tabulators are not allowed.
String literals are enclosed in double quotes. The ``var`` statement declares String literals are enclosed in double-quotes. The ``var`` statement declares
a new variable named ``name`` of type ``string`` with the value that is a new variable named ``name`` of type ``string`` with the value that is
returned by the `readLine <io.html#readLine,File>`_ procedure. Since the returned by the `readLine <io.html#readLine,File>`_ procedure. Since the
compiler knows that `readLine <io.html#readLine,File>`_ returns a string, compiler knows that `readLine <io.html#readLine,File>`_ returns a string,
@ -96,16 +96,16 @@ keywords, comments, operators, and other punctuation marks.
String and character literals String and character literals
----------------------------- -----------------------------
String literals are enclosed in double quotes; character literals in single String literals are enclosed in double-quotes; character literals in single
quotes. Special characters are escaped with ``\``: ``\n`` means newline, ``\t`` quotes. Special characters are escaped with ``\``: ``\n`` means newline, ``\t``
means tabulator, etc. There are also *raw* string literals: means tabulator, etc. There are also *raw* string literals:
.. code-block:: Nim .. code-block:: Nim
r"C:\program files\nim" r"C:\program files\nim"
In raw literals the backslash is not an escape character. In raw literals, the backslash is not an escape character.
The third and last way to write string literals are *long string literals*. The third and last way to write string literals is *long-string literals*.
They are written with three quotes: ``""" ... """``; they can span over They are written with three quotes: ``""" ... """``; they can span over
multiple lines and the ``\`` is not an escape character either. They are very multiple lines and the ``\`` is not an escape character either. They are very
useful for embedding HTML code templates for example. useful for embedding HTML code templates for example.
@ -148,7 +148,7 @@ Numbers
Numerical literals are written as in most other languages. As a special twist, Numerical literals are written as in most other languages. As a special twist,
underscores are allowed for better readability: ``1_000_000`` (one million). underscores are allowed for better readability: ``1_000_000`` (one million).
A number that contains a dot (or 'e' or 'E') is a floating point literal: A number that contains a dot (or 'e' or 'E') is a floating-point literal:
``1.0e9`` (one billion). Hexadecimal literals are prefixed with ``0x``, ``1.0e9`` (one billion). Hexadecimal literals are prefixed with ``0x``,
binary literals with ``0b`` and octal literals with ``0o``. A leading zero binary literals with ``0b`` and octal literals with ``0o``. A leading zero
alone does not produce an octal. alone does not produce an octal.
@ -195,11 +195,11 @@ statement and all the variables will have the same value:
echo "x ", x # outputs "x 42" echo "x ", x # outputs "x 42"
echo "y ", y # outputs "y 3" echo "y ", y # outputs "y 3"
Note that declaring multiple variables with a single assignment which calls a Note that declaring multiple variables with a single assignment that calls a
procedure can have unexpected results: the compiler will *unroll* the procedure can have unexpected results: the compiler will *unroll* the
assignments and end up calling the procedure several times. If the result of assignments and end up calling the procedure several times. If the result of
the procedure depends on side effects, your variables may end up having the procedure depends on side effects, your variables may end up having
different values! For safety use side-effect free procedures if making multiple different values! For safety use side-effect-free procedures if making multiple
assignments. assignments.
@ -296,10 +296,10 @@ a multi-branch:
else: else:
echo "Hi, ", name, "!" echo "Hi, ", name, "!"
As it can be seen, for an ``of`` branch a comma separated list of values is also As it can be seen, for an ``of`` branch a comma-separated list of values is also
allowed. allowed.
The case statement can deal with integers, other ordinal types and strings. The case statement can deal with integers, other ordinal types, and strings.
(What an ordinal type is will be explained soon.) (What an ordinal type is will be explained soon.)
For integers or other ordinal types value ranges are also possible: For integers or other ordinal types value ranges are also possible:
@ -332,7 +332,7 @@ cannot fail and thus the error disappears. Note that it is impossible to cover
all possible string values: that is why string cases always need an ``else`` all possible string values: that is why string cases always need an ``else``
branch. branch.
In general the case statement is used for subrange types or enumerations where In general, the case statement is used for subrange types or enumerations where
it is of great help that the compiler checks that you covered any possible it is of great help that the compiler checks that you covered any possible
value. value.
@ -399,7 +399,7 @@ Since counting up occurs so often in programs, Nim also has a `..
... ...
Zero-indexed counting has two shortcuts ``..<`` and ``.. ^1`` Zero-indexed counting has two shortcuts ``..<`` and ``.. ^1``
(`backwards index operator <system.html#^.t%2Cint>`_) to simplify (`backward index operator <system.html#^.t%2Cint>`_) to simplify
counting to one less than the higher index: counting to one less than the higher index:
.. code-block:: nim .. code-block:: nim
@ -520,7 +520,7 @@ differences:
* The compiler checks the semantics and produces code *only* for the statements * The compiler checks the semantics and produces code *only* for the statements
that belong to the first condition that evaluates to ``true``. that belong to the first condition that evaluates to ``true``.
The ``when`` statement is useful for writing platform specific code, similar to The ``when`` statement is useful for writing platform-specific code, similar to
the ``#ifdef`` construct in the C programming language. the ``#ifdef`` construct in the C programming language.
@ -530,15 +530,15 @@ Statements and indentation
Now that we covered the basic control flow statements, let's return to Nim Now that we covered the basic control flow statements, let's return to Nim
indentation rules. indentation rules.
In Nim there is a distinction between *simple statements* and *complex In Nim, there is a distinction between *simple statements* and *complex
statements*. *Simple statements* cannot contain other statements: statements*. *Simple statements* cannot contain other statements:
Assignment, procedure calls or the ``return`` statement belong to the simple Assignment, procedure calls, or the ``return`` statement are all simple
statements. *Complex statements* like ``if``, ``when``, ``for``, ``while`` can statements. *Complex statements* like ``if``, ``when``, ``for``, ``while`` can
contain other statements. To avoid ambiguities, complex statements must always contain other statements. To avoid ambiguities, complex statements must always
be indented, but single simple statements do not: be indented, but single simple statements do not:
.. code-block:: nim .. code-block:: nim
# no indentation needed for single assignment statement: # no indentation needed for single-assignment statement:
if x: x = false if x: x = false
# indentation needed for nested if statement: # indentation needed for nested if statement:
@ -554,8 +554,8 @@ be indented, but single simple statements do not:
y = false y = false
*Expressions* are parts of a statement which usually result in a value. The *Expressions* are parts of a statement that usually result in a value. The
condition in an if statement is an example for an expression. Expressions can condition in an if statement is an example of an expression. Expressions can
contain indentation at certain places for better readability: contain indentation at certain places for better readability:
.. code-block:: nim .. code-block:: nim
@ -617,7 +617,7 @@ Some terminology: in the example ``question`` is called a (formal) *parameter*,
Result variable Result variable
--------------- ---------------
A procedure that returns a value has an implicit ``result`` variable declared A procedure that returns a value has an implicit ``result`` variable declared
that represents the return value. A ``return`` statement with no expression is a that represents the return value. A ``return`` statement with no expression is
shorthand for ``return result``. The ``result`` value is always returned shorthand for ``return result``. The ``result`` value is always returned
automatically at the end of a procedure if there is no ``return`` statement at automatically at the end of a procedure if there is no ``return`` statement at
the exit. the exit.
@ -637,9 +637,9 @@ the exit.
The ``result`` variable is already implicitly declared at the start of the The ``result`` variable is already implicitly declared at the start of the
function, so declaring it again with 'var result', for example, would shadow it function, so declaring it again with 'var result', for example, would shadow it
with a normal variable of the same name. The result variable is also already with a normal variable of the same name. The result variable is also already
initialised with the type's default value. Note that referential data types will initialized with the type's default value. Note that referential data types will
be ``nil`` at the start of the procedure, and thus may require manual be ``nil`` at the start of the procedure, and thus may require manual
initialisation. initialization.
A procedure that does not have any ``return`` statement and does not use the A procedure that does not have any ``return`` statement and does not use the
special ``result`` variable returns the value of its last expression. For example, special ``result`` variable returns the value of its last expression. For example,
@ -798,7 +798,7 @@ Apart from a few built-in keyword operators such as ``and``, ``or``, ``not``,
operators always consist of these characters: operators always consist of these characters:
``+ - * \ / < > = @ $ ~ & % ! ? ^ . |`` ``+ - * \ / < > = @ $ ~ & % ! ? ^ . |``
User defined operators are allowed. Nothing stops you from defining your own User-defined operators are allowed. Nothing stops you from defining your own
``@!?+~`` operator, but doing so may reduce readability. ``@!?+~`` operator, but doing so may reduce readability.
The operator's precedence is determined by its first character. The details The operator's precedence is determined by its first character. The details
@ -900,13 +900,12 @@ important differences:
``yield`` statement). ``yield`` statement).
* Iterators have no implicit ``result`` variable. * Iterators have no implicit ``result`` variable.
* Iterators do not support recursion. * Iterators do not support recursion.
* Iterators cannot be forward declared, because the compiler must be able * Iterators cannot be forward declared, because the compiler must be able to inline an iterator. (This restriction will be gone in a
to inline an iterator. (This restriction will be gone in a
future version of the compiler.) future version of the compiler.)
However, you can also use a ``closure`` iterator to get a different set of However, you can also use a ``closure`` iterator to get a different set of
restrictions. See `first class iterators <manual.html#iterators-and-the-for-statement-first-class-iterators>`_ restrictions. See `first-class iterators <manual.html#iterators-and-the-for-statement-firstminusclass-iterators>`_
for details. Iterators can have the same name and parameters as a proc, since for details. Iterators can have the same name and parameters as a proc since
essentially they have their own namespaces. Therefore it is common practice to essentially they have their own namespaces. Therefore it is common practice to
wrap iterators in procs of the same name which accumulate the result of the wrap iterators in procs of the same name which accumulate the result of the
iterator and return it as a sequence, like ``split`` from the `strutils module iterator and return it as a sequence, like ``split`` from the `strutils module
@ -940,10 +939,10 @@ evaluation. For example:
Characters Characters
---------- ----------
The `character type` is called ``char``. Its size is always one byte, so The `character type` is called ``char``. Its size is always one byte, so
it cannot represent most UTF-8 characters; but it *can* represent one of the bytes it cannot represent most UTF-8 characters, but it *can* represent one of the bytes
that makes up a multi-byte UTF-8 character. that makes up a multi-byte UTF-8 character.
The reason for this is efficiency: for the overwhelming majority of use-cases, The reason for this is efficiency: for the overwhelming majority of use-cases,
the resulting programs will still handle UTF-8 properly as UTF-8 was specially the resulting programs will still handle UTF-8 properly as UTF-8 was especially
designed for this. designed for this.
Character literals are enclosed in single quotes. Character literals are enclosed in single quotes.
@ -995,7 +994,7 @@ Most often integers are used for counting objects that reside in memory, so
``int`` has the same size as a pointer. ``int`` has the same size as a pointer.
The common operators ``+ - * div mod < <= == != > >=`` are defined for The common operators ``+ - * div mod < <= == != > >=`` are defined for
integers. The ``and or xor not`` operators are also defined for integers, and integers. The ``and or xor not`` operators are also defined for integers and
provide *bitwise* operations. Left bit shifting is done with the ``shl``, right provide *bitwise* operations. Left bit shifting is done with the ``shl``, right
shifting with the ``shr`` operator. Bit shifting operators always treat their shifting with the ``shr`` operator. Bit shifting operators always treat their
arguments as *unsigned*. For `arithmetic bit shifts`:idx: ordinary arguments as *unsigned*. For `arithmetic bit shifts`:idx: ordinary
@ -1012,7 +1011,7 @@ cannot be detected at compile time).
Floats Floats
------ ------
Nim has these floating point types built-in: ``float float32 float64``. Nim has these floating-point types built-in: ``float float32 float64``.
The default float type is ``float``. In the current implementation, The default float type is ``float``. In the current implementation,
``float`` is always 64-bits. ``float`` is always 64-bits.
@ -1030,9 +1029,8 @@ type:
The common operators ``+ - * / < <= == != > >=`` are defined for The common operators ``+ - * / < <= == != > >=`` are defined for
floats and follow the IEEE-754 standard. floats and follow the IEEE-754 standard.
Automatic type conversion in expressions with different kinds of floating Automatic type conversion in expressions with different kinds of floating-point types is performed: the smaller type is converted to the larger. Integer
point types is performed: the smaller type is converted to the larger. Integer types are **not** converted to floating-point types automatically, nor vice
types are **not** converted to floating point types automatically, nor vice
versa. Use the `toInt <system.html#toInt,float>`_ and versa. Use the `toInt <system.html#toInt,float>`_ and
`toFloat <system.html#toFloat,int>`_ procs for these conversions. `toFloat <system.html#toFloat,int>`_ procs for these conversions.
@ -1104,7 +1102,7 @@ Enumerations
A variable of an enumeration type can only be assigned one of the enumeration's specified values. A variable of an enumeration type can only be assigned one of the enumeration's specified values.
These values are a set of ordered symbols. Each symbol is mapped These values are a set of ordered symbols. Each symbol is mapped
to an integer value internally. The first symbol is represented to an integer value internally. The first symbol is represented
at runtime by 0, the second by 1 and so on. For example: at runtime by 0, the second by 1, and so on. For example:
.. code-block:: nim .. code-block:: nim
:test: "nim c $1" :test: "nim c $1"
@ -1135,6 +1133,7 @@ Enumerations, integer types, ``char`` and ``bool`` (and
subranges) are called ordinal types. Ordinal types have quite subranges) are called ordinal types. Ordinal types have quite
a few special operations: a few special operations:
----------------- -------------------------------------------------------- ----------------- --------------------------------------------------------
Operation Comment Operation Comment
----------------- -------------------------------------------------------- ----------------- --------------------------------------------------------
@ -1150,6 +1149,7 @@ Operation Comment
``pred(x, n)`` returns the `n`'th predecessor of `x` ``pred(x, n)`` returns the `n`'th predecessor of `x`
----------------- -------------------------------------------------------- ----------------- --------------------------------------------------------
The `inc <system.html#inc,T,int>`_, `dec <system.html#dec,T,int>`_, `succ The `inc <system.html#inc,T,int>`_, `dec <system.html#dec,T,int>`_, `succ
<system.html#succ,T,int>`_ and `pred <system.html#pred,T,int>`_ operations can <system.html#succ,T,int>`_ and `pred <system.html#pred,T,int>`_ operations can
fail by raising an `EOutOfRange` or `EOverflow` exception. (If the code has been fail by raising an `EOutOfRange` or `EOverflow` exception. (If the code has been
@ -1187,7 +1187,7 @@ Sets
Arrays Arrays
------ ------
An array is a simple fixed length container. Each element in An array is a simple fixed-length container. Each element in
an array has the same type. The array's index type can be any ordinal type. an array has the same type. The array's index type can be any ordinal type.
Arrays can be constructed using ``[]``: Arrays can be constructed using ``[]``:
@ -1240,7 +1240,7 @@ same index type as the others. In Nim you can have different dimensions with
different index types, so the nesting syntax is slightly different. Building on different index types, so the nesting syntax is slightly different. Building on
the previous example where a level is defined as an array of enums indexed by the previous example where a level is defined as an array of enums indexed by
yet another enum, we can add the following lines to add a light tower type yet another enum, we can add the following lines to add a light tower type
subdivided in height levels accessed through their integer index: subdivided into height levels accessed through their integer index:
.. code-block:: nim .. code-block:: nim
type type
@ -1314,7 +1314,7 @@ The ``for`` statement can be used with one or two variables when used with a
sequence. When you use the one variable form, the variable will hold the value sequence. When you use the one variable form, the variable will hold the value
provided by the sequence. The ``for`` statement is looping over the results provided by the sequence. The ``for`` statement is looping over the results
from the `items() <system.html#items.i,seq[T]>`_ iterator from the `system from the `items() <system.html#items.i,seq[T]>`_ iterator from the `system
<system.html>`_ module. But if you use the two variable form, the first <system.html>`_ module. But if you use the two-variable form, the first
variable will hold the index position and the second variable will hold the variable will hold the index position and the second variable will hold the
value. Here the ``for`` statement is looping over the results from the value. Here the ``for`` statement is looping over the results from the
`pairs() <system.html#pairs.i,seq[T]>`_ iterator from the `system `pairs() <system.html#pairs.i,seq[T]>`_ iterator from the `system
@ -1339,7 +1339,7 @@ Open arrays
----------- -----------
**Note**: Openarrays can only be used for parameters. **Note**: Openarrays can only be used for parameters.
Often fixed size arrays turn out to be too inflexible; procedures should be Often fixed-size arrays turn out to be too inflexible; procedures should be
able to deal with arrays of different sizes. The `openarray`:idx: type allows able to deal with arrays of different sizes. The `openarray`:idx: type allows
this. Openarrays are always indexed with an ``int`` starting at position 0. this. Openarrays are always indexed with an ``int`` starting at position 0.
The `len <system.html#len,TOpenArray>`_, `low <system.html#low,openArray[T]>`_ The `len <system.html#len,TOpenArray>`_, `low <system.html#low,openArray[T]>`_
@ -1591,10 +1591,10 @@ having the same field types.
Tuples can be *unpacked* during variable assignment (and only then!). This can Tuples can be *unpacked* during variable assignment (and only then!). This can
be handy to assign directly the fields of the tuples to individually named be handy to assign directly the fields of the tuples to individually named
variables. An example of this is the `splitFile <os.html#splitFile,string>`_ variables. An example of this is the `splitFile <os.html#splitFile,string>`_
proc from the `os module <os.html>`_ which returns the directory, name and proc from the `os module <os.html>`_ which returns the directory, name, and
extension of a path at the same time. For tuple unpacking to work you must extension of a path at the same time. For tuple unpacking to work you must
use parentheses around the values you want to assign the unpacking to, use parentheses around the values you want to assign the unpacking to,
otherwise you will be assigning the same value to all the individual otherwise, you will be assigning the same value to all the individual
variables! For example: variables! For example:
.. code-block:: nim .. code-block:: nim
@ -1626,15 +1626,15 @@ point to and modify the same location in memory.
Nim distinguishes between `traced`:idx: and `untraced`:idx: references. Nim distinguishes between `traced`:idx: and `untraced`:idx: references.
Untraced references are also called *pointers*. Traced references point to Untraced references are also called *pointers*. Traced references point to
objects in a garbage collected heap, untraced references point to objects in a garbage-collected heap, untraced references point to
manually allocated objects or to objects elsewhere in memory. Thus manually allocated objects or objects elsewhere in memory. Thus
untraced references are *unsafe*. However for certain low-level operations untraced references are *unsafe*. However, for certain low-level operations
(e.g., accessing the hardware), untraced references are necessary. (e.g., accessing the hardware), untraced references are necessary.
Traced references are declared with the **ref** keyword; untraced references Traced references are declared with the **ref** keyword; untraced references
are declared with the **ptr** keyword. are declared with the **ptr** keyword.
The empty ``[]`` subscript notation can be used to *derefer* a reference, The empty ``[]`` subscript notation can be used to *de-refer* a reference,
meaning to retrieve the item the reference points to. The ``.`` (access a meaning to retrieve the item the reference points to. The ``.`` (access a
tuple/object field operator) and ``[]`` (array/string/sequence index operator) tuple/object field operator) and ``[]`` (array/string/sequence index operator)
operators perform implicit dereferencing operations for reference types: operators perform implicit dereferencing operations for reference types:
@ -1688,9 +1688,9 @@ listed in the `manual <manual.html#types-procedural-type>`_.
Distinct type Distinct type
------------- -------------
A Distinct type allows for the creation of new type that "does not imply a A Distinct type allows for the creation of a new type that "does not imply a
subtype relationship between it and its base type". subtype relationship between it and its base type".
You must **explicitly** define all behaviour for the distinct type. You must **explicitly** define all behavior for the distinct type.
To help with this, both the distinct type and its base type can cast from one To help with this, both the distinct type and its base type can cast from one
type to the other. type to the other.
Examples are provided in the `manual <manual.html#types-distinct-type>`_. Examples are provided in the `manual <manual.html#types-distinct-type>`_.
@ -1775,7 +1775,7 @@ Excluding symbols
----------------- -----------------
The normal ``import`` statement will bring in all exported symbols. The normal ``import`` statement will bring in all exported symbols.
These can be limited by naming symbols which should be excluded with These can be limited by naming symbols that should be excluded using
the ``except`` qualifier. the ``except`` qualifier.
.. code-block:: nim .. code-block:: nim
@ -1794,7 +1794,7 @@ exported symbols. An alternative that only imports listed symbols is the
The ``from`` statement can also force namespace qualification on The ``from`` statement can also force namespace qualification on
symbols, thereby making symbols available, but needing to be qualified symbols, thereby making symbols available, but needing to be qualified
to be used. in order to be used.
.. code-block:: nim .. code-block:: nim
from mymodule import x, y, z from mymodule import x, y, z

View file

@ -14,7 +14,7 @@ Introduction
"With Great Power Comes Great Responsibility." -- Spider Man's Uncle "With Great Power Comes Great Responsibility." -- Spider Man's Uncle
This document is a tutorial about Nim's macro system. This document is a tutorial about Nim's macro system.
A macro is a function that is executed at compile time and transforms A macro is a function that is executed at compile-time and transforms
a Nim syntax tree into a different tree. a Nim syntax tree into a different tree.
Examples of things that can be implemented in macros: Examples of things that can be implemented in macros:
@ -35,7 +35,7 @@ Macro Arguments
--------------- ---------------
The types of macro arguments have two faces. One face is used for The types of macro arguments have two faces. One face is used for
the overload resolution, and the other face is used within the macro the overload resolution and the other face is used within the macro
body. For example, if ``macro foo(arg: int)`` is called in an body. For example, if ``macro foo(arg: int)`` is called in an
expression ``foo(x)``, ``x`` has to be of a type compatible to int, but expression ``foo(x)``, ``x`` has to be of a type compatible to int, but
*within* the macro's body ``arg`` has the type ``NimNode``, not ``int``! *within* the macro's body ``arg`` has the type ``NimNode``, not ``int``!
@ -52,10 +52,10 @@ Untyped Arguments
Untyped macro arguments are passed to the macro before they are Untyped macro arguments are passed to the macro before they are
semantically checked. This means the syntax tree that is passed down semantically checked. This means the syntax tree that is passed down
to the macro does not need to make sense for Nim yet, the only to the macro does not need to make sense for Nim yet, the only
limitation is that it needs to be parsable. Usually the macro does limitation is that it needs to be parsable. Usually, the macro does
not check the argument either but uses it in the transformation's not check the argument either but uses it in the transformation's
result somehow. The result of a macro expansion is always checked result somehow. The result of a macro expansion is always checked
by the compiler, so apart from weird error messages nothing bad by the compiler, so apart from weird error messages, nothing bad
can happen. can happen.
The downside for an ``untyped`` argument is that these do not play The downside for an ``untyped`` argument is that these do not play
@ -73,7 +73,7 @@ For typed arguments, the semantic checker runs on the argument and
does transformations on it, before it is passed to the macro. Here does transformations on it, before it is passed to the macro. Here
identifier nodes are resolved as symbols, implicit type identifier nodes are resolved as symbols, implicit type
conversions are visible in the tree as calls, templates are conversions are visible in the tree as calls, templates are
expanded and probably most importantly, nodes have type information. expanded, and probably most importantly, nodes have type information.
Typed arguments can have the type ``typed`` in the arguments list. Typed arguments can have the type ``typed`` in the arguments list.
But all other types, such as ``int``, ``float`` or ``MyObjectType`` But all other types, such as ``int``, ``float`` or ``MyObjectType``
are typed arguments as well, and they are passed to the macro as a are typed arguments as well, and they are passed to the macro as a
@ -103,7 +103,7 @@ Code Blocks as Arguments
------------------------ ------------------------
It is possible to pass the last argument of a call expression in a It is possible to pass the last argument of a call expression in a
separate code block with indentation. For example the following code separate code block with indentation. For example, the following code
example is a valid (but not a recommended) way to call ``echo``: example is a valid (but not a recommended) way to call ``echo``:
.. code-block:: nim .. code-block:: nim
@ -126,10 +126,10 @@ look like so that the Nim compiler will understand it. The nodes of the
Nim syntax tree are documented in the `macros <macros.html>`_ module. Nim syntax tree are documented in the `macros <macros.html>`_ module.
But a more interactive way to explore the Nim But a more interactive way to explore the Nim
syntax tree is with ``macros.treeRepr``, it converts a syntax tree syntax tree is with ``macros.treeRepr``, it converts a syntax tree
into a multi line string for printing on the console. It can be used into a multi-line string for printing on the console. It can be used
to explore how the argument expressions are represented in tree form to explore how the argument expressions are represented in tree form
and for debug printing of generated syntax tree. ``dumpTree`` is a and for debug printing of generated syntax tree. ``dumpTree`` is a
predefined macro that just prints its argument in tree representation, predefined macro that just prints its argument in a tree representation,
but does nothing else. Here is an example of such a tree representation: but does nothing else. Here is an example of such a tree representation:
.. code-block:: nim .. code-block:: nim
@ -176,7 +176,7 @@ Generating Code
There are two ways to generate the code. Either by creating the syntax There are two ways to generate the code. Either by creating the syntax
tree with expressions that contain a lot of calls to ``newTree`` and tree with expressions that contain a lot of calls to ``newTree`` and
``newLit``, or with ``quote do:`` expressions. The first option offers ``newLit``, or with ``quote do:`` expressions. The first option offers
the best low level control for the syntax tree generation, but the the best low-level control for the syntax tree generation, but the
second option is much less verbose. If you choose to create the syntax second option is much less verbose. If you choose to create the syntax
tree with calls to ``newTree`` and ``newLit`` the macro tree with calls to ``newTree`` and ``newLit`` the macro
``macros.dumpAstGen`` can help you with the verbosity. ``quote do:`` ``macros.dumpAstGen`` can help you with the verbosity. ``quote do:``
@ -226,8 +226,8 @@ Building Your First Macro
To give a starting point to writing macros we will show now how to To give a starting point to writing macros we will show now how to
implement the ``myDebug`` macro mentioned earlier. The first thing to implement the ``myDebug`` macro mentioned earlier. The first thing to
do is to build a simple example of the macro usage, and then just do is to build a simple example of the macro usage, and then just
print the argument. This way it is possible to get an idea of a print the argument. This way it is possible to get an idea of what a
correct argument should be look like. correct argument should look like.
.. code-block:: nim .. code-block:: nim
:test: "nim c $1" :test: "nim c $1"
@ -250,9 +250,9 @@ correct argument should be look like.
Ident "b" Ident "b"
From the output it is possible to see that the argument is an infix From the output, it is possible to see that the argument is an infix
operator (node kind is "Infix"), as well as that the two operands are operator (node kind is "Infix"), as well as that the two operands are
at index 1 and 2. With this information the actual macro can be at index 1 and 2. With this information, the actual macro can be
written. written.
.. code-block:: nim .. code-block:: nim
@ -292,13 +292,13 @@ used to get this output.
With Power Comes Responsibility With Power Comes Responsibility
------------------------------- -------------------------------
Macros are very powerful. A good advice is to use them as little as Macros are very powerful. A piece of good advice is to use them as little as
possible, but as much as necessary. Macros can change the semantics of possible, but as much as necessary. Macros can change the semantics of
expressions, making the code incomprehensible for anybody who does not expressions, making the code incomprehensible for anybody who does not
know exactly what the macro does with it. So whenever a macro is not know exactly what the macro does with it. So whenever a macro is not
necessary and the same logic can be implemented using templates or necessary and the same logic can be implemented using templates or
generics, it is probably better not to use a macro. And when a macro generics, it is probably better not to use a macro. And when a macro
is used for something, the macro should better have a well written is used for something, the macro should better have a well-written
documentation. For all the people who claim to write only perfectly documentation. For all the people who claim to write only perfectly
self-explanatory code: when it comes to macros, the implementation is self-explanatory code: when it comes to macros, the implementation is
not enough for documentation. not enough for documentation.
@ -309,7 +309,7 @@ Limitations
Since macros are evaluated in the compiler in the NimVM, macros share Since macros are evaluated in the compiler in the NimVM, macros share
all the limitations of the NimVM. They have to be implemented in pure Nim all the limitations of the NimVM. They have to be implemented in pure Nim
code. Macros can start external processes on the shell, but they code. Macros can start external processes on the shell, but they
cannot call C functions except from those that are built in the cannot call C functions except those that are built in the
compiler. compiler.
@ -348,7 +348,7 @@ OpenGL Sandbox
-------------- --------------
This project has a working Nim to GLSL compiler written entirely in This project has a working Nim to GLSL compiler written entirely in
macros. It scans recursively though all used function symbols to macros. It scans recursively through all used function symbols to
compile them so that cross library functions can be executed on the GPU. compile them so that cross library functions can be executed on the GPU.
`OpenGL Sandbox <https://github.com/krux02/opengl-sandbox>`_ `OpenGL Sandbox <https://github.com/krux02/opengl-sandbox>`_