diff --git a/doc/apis.rst b/doc/apis.rst index d0327c76ec74a..03374c2db0568 100644 --- a/doc/apis.rst +++ b/doc/apis.rst @@ -3,7 +3,7 @@ API naming design ================= 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 diff --git a/doc/backends.rst b/doc/backends.rst index e46941a12eeae..b50c7e38fb9b8 100644 --- a/doc/backends.rst +++ b/doc/backends.rst @@ -15,16 +15,16 @@ Introduction The `Nim Compiler User Guide `_ documents the typical 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 -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 +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 concentrate in a single place all the backend and interfacing options. The Nim compiler supports mainly two backend families: the C, C++ and 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 <#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 `_. 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`` 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 -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:: $ nim c hallo.nim @@ -56,8 +56,8 @@ line invocations:: $ nim objc hallo.nim The compiler commands select the target backend, but if needed you can -`specify additional switches for cross compilation -`_ to select the target CPU, operative system +`specify additional switches for cross-compilation +`_ to select the target CPU, operative system or compiler/linker commands. @@ -79,7 +79,7 @@ available. This includes: * OS-specific operations * threading, coroutines * 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 `_ @@ -119,7 +119,7 @@ pragmas to call methods from classes. 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 -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``. 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 ``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 -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:: $ 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 `dom module `_ for specific DOM querying and modification procs or take a look at `karax `_ for how to -develop browser based applications. +develop browser-based applications. Backend code calling Nim @@ -220,7 +220,7 @@ Backend code calling Nim Backend code can interface with Nim code exposed through the `exportc pragma `_. The ``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 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. @@ -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. 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 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 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 -earlier, JavaScript doesn't require an initialisation call to ``NimMain`` or -similar function and you can call the exported Nim proc directly. +earlier, JavaScript doesn't require an initialization call to ``NimMain`` or +a similar function and you can call the exported Nim proc directly. 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 name for the directory depends on the used backend and on your OS but you can use the ``--nimcache`` `compiler switch -`_ to change it. +`_ to change it. 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 -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 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 @@ -355,7 +355,7 @@ The manual mentions that `Nim strings are implicitly convertible to cstrings `_ which makes interaction usually painless. Most C functions accepting a Nim string converted to a ``cstring`` will likely not need to keep this string around and by the time -they return the string won't be needed any more. However, for the rare cases +they return the string won't be needed anymore. However, for the rare cases where a Nim string has to be preserved and made available to the C backend as a ``cstring``, you will need to manually prevent the string data from being freed with `GC_ref `_ and `GC_unref @@ -388,7 +388,7 @@ to hand a Nim reference to C code, you will need to use `GC_ref `_ to mark the reference as used, so it does not get freed. And for the C backend you will need to expose the `GC_unref `_ proc to clean up this memory when it is not -required any more. +required anymore. Again, if you are wrapping a library which *mallocs* and *frees* data structures, you need to expose the appropriate *free* function to Nim so @@ -424,4 +424,3 @@ leaks by calling .. code-block:: nim system.tearDownForeignThreadGc() - diff --git a/doc/destructors.rst b/doc/destructors.rst index b581fce3e25de..ff09d66445921 100644 --- a/doc/destructors.rst +++ b/doc/destructors.rst @@ -25,7 +25,7 @@ move semantics and destructors work in Nim. 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: .. code-block:: nim @@ -88,7 +88,7 @@ Lifetime-tracking hooks ======================= 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 hooks for each (generic or concrete) object type ``T`` (``T`` can also be a ``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 -and passed to the destination. It is ensured that source's destructor does -not free the resources afterwards by setting the object to its default value +and passed to the destination. It is ensured that the source's destructor does +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 default value is written as ``wasMoved(x)``. When not provided the compiler 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 -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: @@ -191,7 +191,7 @@ Move semantics ============== 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 used afterwards. This property is computed by a static control flow analysis 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. -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 proven to be the last usage of the location, a copy is done instead and this 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. 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 @@ -509,7 +509,7 @@ to avoid this overhead: 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 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 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 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 words, we do a compile-time copy-on-write analysis. @@ -547,9 +547,9 @@ other words, a copy ``x = y`` is implemented 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 -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 -of the involved datastructure 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. diff --git a/doc/docgen.rst b/doc/docgen.rst index 636af6574a394..07218982c011b 100644 --- a/doc/docgen.rst +++ b/doc/docgen.rst @@ -14,7 +14,7 @@ Introduction This document describes the `documentation generation tools`:idx: built into the `Nim compiler `_, which can generate HTML and JSON output 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 exported symbols (*), including procedures, types, and variables. @@ -107,7 +107,7 @@ Document Types 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 base filename, or multiple .nim files, outputting multiple .html files and, optionally, an index file. @@ -121,15 +121,15 @@ Partial Output:: ... The full output can be seen here: `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. JSON ---- -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 +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 that this tool is built off of the ``doc`` command (previously ``doc2``), and contains the same information. @@ -153,8 +153,8 @@ Output:: ] } -Similarly to the old ``doc`` command the old ``jsondoc`` command has been -renamed ``jsondoc0``. +Similarly to the old ``doc`` command, the old ``jsondoc`` command has been +renamed to ``jsondoc0``. The ``jsondoc0`` command:: nim jsondoc0 sample @@ -197,8 +197,8 @@ Index switch 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 -index file is line oriented (newlines have to be escaped). Each line -represents a tab separated record of several columns, the first two mandatory, +index file is line-oriented (newlines have to be escaped). Each line +represents a tab-separated record of several columns, the first two mandatory, 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 @@ -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 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 also allows specifying a ``githash`` value in ``web/website.ini`` to force a 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 -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 +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 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 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 signature. Variables or constants have the same plain name symbol as their complex name. The plain name for procs, templates, and other callable types -will be their unquoted value after removing parameters, return types and -pragmas. The plain name allows short and nice linking of symbols which works +will be their unquoted value after removing parameters, return types, and +pragmas. The plain name allows short and nice linking of symbols that works 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 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 -made up from several parts: +made up of several parts: (**plain symbol**)(**.type**),(**first param**)?(**,param type**)\* 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 -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: ------------- -------------- @@ -337,15 +337,15 @@ references so they can be later concatenated into a big index file with `mergeIndexes() `_. This section documents the file format in detail. -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, +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 but can have up to four (additional columns are ignored). The content of these columns is: 1. Mandatory term being indexed. Terms can include quoting according to Nim's rules (e.g. \`^\`). 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 using the term. Prefix whitespace indicates that this entry is 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 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 -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 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 to the word **Module**. 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 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 @@ -379,14 +379,14 @@ final index, and TOC entries found in ``.nim`` files are discarded. Additional resources ==================== -`Nim Compiler User Guide `_ +`Nim Compiler User Guide `_ `RST Quick Reference `_ 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 -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 `_ in your programs if you want to reuse the compiler's documentation generation procs. diff --git a/doc/drnim.rst b/doc/drnim.rst index 5351daac90ee4..ee6e0ea172bc4 100644 --- a/doc/drnim.rst +++ b/doc/drnim.rst @@ -13,8 +13,8 @@ Introduction This document describes the usage of the *DrNim* tool. DrNim combines the Nim frontend with the `Z3 `_ proof -engine in order to allow verify / validate software written in Nim. -DrNim's command line options are the same as the Nim compiler's. +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 currently only checks the sections of your code that are marked @@ -140,8 +140,8 @@ Example: insertionSort swap a[t], a[t-1] dec t -Unfortunately the invariants required to prove this code correct take more -code than the imperative instructions. However this effort can be compensated +Unfortunately, the invariants required to prove that this code is correct take more +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 DrNim only proves that after ``insertionSort`` this condition holds:: diff --git a/doc/hcr.rst b/doc/hcr.rst index 55ccc06dc7047..d2e13e1c7d101 100644 --- a/doc/hcr.rst +++ b/doc/hcr.rst @@ -14,11 +14,11 @@ preserved. 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 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 ``#***``. 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 -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. diff --git a/doc/koch.rst b/doc/koch.rst index e984a71ea459e..01c69081644ce 100644 --- a/doc/koch.rst +++ b/doc/koch.rst @@ -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 https://nim-lang.org. -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 +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 be rerun in serial fashion so that meaningful error output can be gathered for inspection. The ``--parallelBuild:n`` switch or configuration option can be used to force a specific number of parallel jobs or run everything serially diff --git a/doc/lib.rst b/doc/lib.rst index e05657b42ed8f..2dd43109eb346 100644 --- a/doc/lib.rst +++ b/doc/lib.rst @@ -7,7 +7,7 @@ Nim Standard Library .. 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 while impure libraries do. A wrapper is an impure library that is a very @@ -32,7 +32,7 @@ Automatic imports * `system `_ Basic procs and operators that every program needs. It also provides IO facilities for reading and writing text and binary files. It is imported - implicitly by the compiler. Do not import it directly. It relies on compiler + implicitly by the compiler. Do not import it directly. It relies on compiler magic to work. * `threads `_ @@ -48,7 +48,7 @@ Core ---- * `bitops `_ - Provides a series of low level methods for bit manipulation. + Provides a series of low-level methods for bit manipulation. * `cpuinfo `_ This module implements procs to determine the number of CPUs / cores. @@ -69,7 +69,7 @@ Core Reentrant locks for Nim. * `typeinfo `_ - Provides (unsafe) access to Nim's run time type information. + Provides (unsafe) access to Nim's run-time type information. * `typetraits `_ This module defines compile-time reflection procs for working with types. @@ -83,7 +83,7 @@ Algorithms ---------- * `algorithm `_ - Implements some common generic algorithms like sort or binary search. + This module implements some common generic algorithms like sort or binary search. * `sequtils `_ This module implements operations for the built-in seq type @@ -96,7 +96,7 @@ Collections * `critbits `_ 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 `_ Implementation of a double-ended queue. @@ -119,13 +119,13 @@ Collections Nim hash and bit set support. * `sharedlist `_ - Nim shared linked list support. Contains shared singly linked list. + Nim shared linked list support. Contains a shared singly-linked list. * `sharedtables `_ Nim shared hash table support. Contains shared tables. * `tables `_ - Nim hash table support. Contains tables, ordered tables and count tables. + Nim hash table support. Contains tables, ordered tables, and count tables. @@ -154,11 +154,11 @@ String handling * `ropes `_ This module contains support for a *rope* data type. - Ropes can represent very long strings efficiently; especially concatenation - is done in O(1) instead of O(n). + Ropes can represent very long strings efficiently; + especially concatenation is done in O(1) instead of O(n). * `strformat `_ - Macro based standard string interpolation / formatting. Inspired by + Macro based standard string interpolation/formatting. Inspired by Python's ``f``-strings. * `strmisc `_ @@ -207,7 +207,7 @@ Generic Operating System Services and the OS's native package manager. Its primary purpose is to produce output for Nimble packages, 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 `_ for hints on distributing Nim using OS packages. * `dynlib `_ @@ -218,7 +218,7 @@ Generic Operating System Services data structures. * `memfiles `_ - 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. * `os `_ @@ -231,8 +231,8 @@ Generic Operating System Services * `streams `_ This module provides a stream interface and two implementations thereof: - the `FileStream` and the `StringStream` which implement the stream - interface for Nim file objects (`File`) and strings. Other modules + the `FileStream` and the `StringStream` which implement the stream + interface for Nim file objects (`File`) and strings. Other modules may provide other implementations for this standard stream interface. * `terminal `_ @@ -245,7 +245,7 @@ Math libraries -------------- * `complex `_ - This module implements complex numbers and their mathematical operations. + This module implements complex numbers and relevant mathematical operations. * `fenv `_ Floating-point environment. Handling of floating-point rounding and @@ -261,7 +261,7 @@ Math libraries Fast and tiny random number generator. * `rationals `_ - This module implements rational numbers and their mathematical operations. + This module implements rational numbers and relevant mathematical operations. * `stats `_ Statistical analysis @@ -317,10 +317,10 @@ Internet Protocols and Support * `selectors `_ 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 `_ - This module implement a simple SMTP client. + This module implements a simple SMTP client. * `uri `_ 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. * `json `_ - High performance JSON parser. + High-performance JSON parser. * `lexbase `_ - 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. * `parsecfg `_ - 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`` 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. * `parsecsv `_ - The ``parsecsv`` module implements a simple high performance CSV parser. + The ``parsecsv`` module implements a simple high-performance CSV parser. * `parseopt `_ The ``parseopt`` module implements a command line option parser. * `parsesql `_ - The ``parsesql`` module implements a simple high performance SQL parser. + The ``parsesql`` module implements a simple high-performance SQL parser. * `parsexml `_ 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 - to be somewhat error correcting, so that even some "wild HTML" found on the - Web can be parsed with it. + to be somewhat error-correcting, so that even some "wild HTML" found on the + web can be parsed with it. Docutils -------- * `packages/docutils/highlite `_ - Source highlighter for programming or markup languages. Currently - only few languages are supported, other languages may be added. + Source highlighter for programming or markup languages. Currently, + only a few languages are supported, other languages may be added. The interface supports one language nested in another. * `packages/docutils/rst `_ - This module implements a reStructuredText parser. A large subset - is implemented. Some features of the markdown wiki syntax are - also supported. + This module implements a reStructuredText parser. A large subset + is implemented. Some features of the markdown wiki syntax are also supported. * `packages/docutils/rstast `_ This module implements an AST for the reStructuredText parser. @@ -404,8 +403,8 @@ Generators ---------- * `htmlgen `_ - This module implements a simple XML and HTML code - generator. Each commonly used HTML tag has a corresponding macro + This module implements a simple XML and HTML code + generator. Each commonly used HTML tag has a corresponding macro that generates a string with its HTML representation. @@ -425,7 +424,7 @@ Hashing * `oids `_ 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 from the Mongodb interface and it thus binary compatible with a Mongo OID. @@ -460,7 +459,7 @@ Miscellaneous Implements a Unit testing DSL. * `std/varints `_ - Decode variable length integers that are compatible with SQLite. + Decode variable-length integers that are compatible with SQLite. Modules for JS backend @@ -476,7 +475,7 @@ Modules for JS backend Wrapper for the ``console`` object. * `jscore `_ - 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. * `jsffi `_ @@ -490,7 +489,7 @@ Regular expressions ------------------- * `re `_ - This module contains procedures and operators for handling regular + This module contains procedures and operators for handling regular expressions. The current implementation uses PCRE. @@ -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. -Windows specific +Windows-specific ---------------- * `winlean `_ @@ -545,7 +544,7 @@ GUI libraries ------------- * `iup `_ - Wrapper of the IUP GUI library. + The wrapper of the IUP GUI library. Database support diff --git a/doc/manual.rst b/doc/manual.rst index ca53999acfaad..d09bb4c76528e 100644 --- a/doc/manual.rst +++ b/doc/manual.rst @@ -8,8 +8,8 @@ Nim Manual .. contents:: - "Complexity" seems to be a lot like "energy": you can transfer it from the end - user to one/some of the other players, but the total amount seems to remain + "Complexity" seems to be a lot like "energy": you can transfer it from the + end-user to one/some of the other players, but the total amount seems to remain pretty much constant for a given task. -- Ran @@ -22,7 +22,7 @@ precise wording. This manual is constantly evolving into a proper specification. **Note**: The experimental features of Nim are covered `here `_. -**Note**: Assignments, moves and destruction are specified in +**Note**: Assignments, moves, and destruction are specified in the `destructors `_ document. @@ -90,9 +90,9 @@ for example, be a native binary or JavaScript source code. In a typical Nim program, most of the code is compiled into the executable. However, some of the code may be executed at -`compile time`:idx:. This can include constant expressions, macro definitions, +`compile-time`:idx:. This can include constant expressions, macro definitions, and Nim procedures used by macro definitions. Most of the Nim language is -supported at compile time, but there are some restrictions -- see `Restrictions +supported at compile-time, but there are some restrictions -- see `Restrictions on Compile-Time Execution <#restrictions-on-compileminustime-execution>`_ for details. We use the term `runtime`:idx: to cover both compile-time execution and code execution in the executable. @@ -125,18 +125,18 @@ compiler may instead choose to allow the program to die with a fatal error. echo "invalid index" The current implementation allows to switch between these different behaviors -via ``--panics:on|off``. When panics are turned on, the program dies on a +via ``--panics:on|off``. When panics are turned on, the program dies with a panic, if they are turned off the runtime errors are turned into exceptions. The benefit of ``--panics:on`` is that it produces smaller binary code and the compiler has more freedom to optimize the code. An `unchecked runtime error`:idx: is an error that is not guaranteed to be -detected, and can cause the subsequent behavior of the computation to +detected and can cause the subsequent behavior of the computation to be arbitrary. Unchecked runtime errors cannot occur if only `safe`:idx: language features are used and if no runtime checks are disabled. A `constant expression`:idx: is an expression whose value can be computed during -semantic analysis of the code in which it appears. It is never an l-value and +a semantic analysis of the code in which it appears. It is never an l-value and never has side effects. Constant expressions are not limited to the capabilities of semantic analysis, such as constant folding; they can use all Nim language features that are supported for compile-time execution. Since constant @@ -163,7 +163,7 @@ encodings are not supported. Any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be -used equally, regardless of platform. +used equally, regardless of the platform. Indentation @@ -180,7 +180,7 @@ lookahead. The parser uses a stack of indentation levels: the stack consists of integers counting the spaces. The indentation information is queried at strategic -places in the parser but ignored otherwise: The pseudo terminal ``IND{>}`` +places in the parser but ignored otherwise: The pseudo-terminal ``IND{>}`` denotes an indentation that consists of more spaces than the entry at the top of the stack; ``IND{=}`` an indentation that has the same number of spaces. ``DED`` is another pseudo terminal that describes the *action* of popping a value @@ -265,7 +265,7 @@ and underscores, with the following restrictions: digit ::= '0'..'9' IDENTIFIER ::= letter ( ['_'] (letter | digit) )* -Currently any Unicode character with an ordinal value > 127 (non ASCII) is +Currently, any Unicode character with an ordinal value > 127 (non-ASCII) is classified as a ``letter`` and may thus be part of an identifier but later versions of the language may assign some Unicode characters to belong to the operator characters instead. @@ -289,11 +289,11 @@ Two identifiers are considered equal if the following algorithm returns true: a[0] == b[0] and a.replace("_", "").toLowerAscii == b.replace("_", "").toLowerAscii -That means only the first letters are compared in a case sensitive manner. Other -letters are compared case insensitively within the ASCII range and underscores are ignored. +That means only the first letters are compared in a case-sensitive manner. Other +letters are compared case-insensitively within the ASCII range and underscores are ignored. This rather unorthodox way to do identifier comparisons is called -`partial case insensitivity`:idx: and has some advantages over the conventional +`partial case-insensitivity`:idx: and has some advantages over the conventional case sensitivity: It allows programmers to mostly use their own preferred @@ -455,7 +455,7 @@ literals: exactly two hex digits are allowed ================== =================================================== -A character is not an Unicode character but a single byte. The reason for this +A character is not a Unicode character but a single byte. 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 designed for this. Another reason is that Nim can thus support ``array[char, int]`` or @@ -504,18 +504,18 @@ Numerical constants are of a single type and have the form:: As can be seen in the productions, numerical constants can contain underscores -for readability. Integer and floating point literals may be given in decimal (no -prefix), binary (prefix ``0b``), octal (prefix ``0o``) and hexadecimal +for readability. Integer and floating-point literals may be given in decimal (no +prefix), binary (prefix ``0b``), octal (prefix ``0o``), and hexadecimal (prefix ``0x``) notation. There exists a literal for each numerical type that is defined. The suffix starting with an apostrophe ('\'') is called a -`type suffix`:idx:. Literals without a type suffix are of an integer type, +`type suffix`:idx:. Literals without a type suffix are of an integer type unless the literal contains a dot or ``E|e`` in which case it is of type ``float``. This integer type is ``int`` if the literal is in the range ``low(i32)..high(i32)``, otherwise it is ``int64``. -For notational convenience the apostrophe of a type suffix -is optional if it is not ambiguous (only hexadecimal floating point literals +For notational convenience, the apostrophe of a type suffix +is optional if it is not ambiguous (only hexadecimal floating-point literals with a type suffix can be ambiguous). @@ -539,12 +539,12 @@ The type suffixes are: ``'f64`` float64 ================= ========================= -Floating point literals may also be in binary, octal or hexadecimal +Floating-point literals may also be in binary, octal or hexadecimal notation: ``0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64`` -is approximately 1.72826e35 according to the IEEE floating point standard. +is approximately 1.72826e35 according to the IEEE floating-point standard. -Literals are bounds checked so that they fit the datatype. Non base-10 +Literals are bounds checked so that they fit the datatype. Non-base-10 literals are used mainly for flags and bit pattern representations, therefore bounds checking is done on bit width, not value range. If the literal fits in the bit width of the datatype, it is accepted. @@ -626,7 +626,7 @@ operator which binds stronger than a ``primarySuffix``: ``@x.abc`` is parsed as ``(@x).abc`` whereas ``$x.abc`` is parsed as ``$(x.abc)``. -For binary operators that are not keywords the precedence is determined by the +For binary operators that are not keywords, the precedence is determined by the following rules: Operators ending in either ``->``, ``~>`` or ``=>`` are called @@ -634,9 +634,9 @@ Operators ending in either ``->``, ``~>`` or ``=>`` are called If the operator ends with ``=`` and its first character is none of ``<``, ``>``, ``!``, ``=``, ``~``, ``?``, it is an *assignment operator* which -has the second lowest precedence. +has the second-lowest precedence. -Otherwise precedence is determined by the first character. +Otherwise, precedence is determined by the first character. ================ ======================================================= ================== =============== Precedence level Operators First character Terminal symbol @@ -664,7 +664,7 @@ whitespace (this parsing change was introduced with version 0.13.0): echo($foo) -Spacing also determines whether ``(a, b)`` is parsed as an the argument list +Spacing also determines whether ``(a, b)`` is parsed as an argument list of a call or whether it is parsed as a tuple constructor: .. code-block:: nim @@ -798,7 +798,7 @@ block. The ability to access and modify compile-time variables adds flexibility to constant expressions that may be surprising to those coming from other statically typed languages. For example, the following code echoes the beginning -of the Fibonacci series **at compile time**. (This is a demonstration of +of the Fibonacci series **at compile-time**. (This is a demonstration of flexibility in defining constants, not a recommended style for solving this problem!) @@ -854,7 +854,7 @@ Some or all of these restrictions are likely to be lifted over time. Types ===== -All expressions have a type which is known during semantic analysis. Nim +All expressions have a type that is known during semantic analysis. Nim is statically typed. One can declare new types, which is in essence defining an identifier that can be used to denote this custom type. @@ -862,7 +862,7 @@ These are the major type classes: * ordinal types (consist of integer, bool, character, enumeration (and subranges thereof) types) -* floating point types +* floating-point types * string type * structured types * reference (pointer) type @@ -877,12 +877,12 @@ Ordinal types have the following characteristics: - Ordinal types are countable and ordered. This property allows the operation of functions as ``inc``, ``ord``, ``dec`` on ordinal types to be defined. -- Ordinal values have a smallest possible value. Trying to count further +- Ordinal values have the smallest possible value. Trying to count further down than the smallest value produces a panic or a static error. -- Ordinal values have a largest possible value. Trying to count further +- Ordinal values have the largest possible value. Trying to count further than the largest value produces a panic or a static error. -Integers, bool, characters and enumeration types (and subranges of these +Integers, bool, characters, and enumeration types (and subranges of these types) belong to ordinal types. For reasons of simplicity of implementation the types ``uint`` and ``uint64`` are not ordinal types. (This will be changed in later versions of the language.) @@ -895,25 +895,23 @@ Pre-defined integer types These integer types are pre-defined: ``int`` - the generic signed integer type; its size is platform dependent and has the + the generic signed integer type; its size is platform-dependent and has the same size as a pointer. This type should be used in general. An integer literal that has no type suffix is of this type if it is in the range ``low(int32)..high(int32)`` otherwise the literal's type is ``int64``. intXX additional signed integer types of XX bits use this naming scheme - (example: int16 is a 16 bit wide integer). + (example: int16 is a 16-bit wide integer). The current implementation supports ``int8``, ``int16``, ``int32``, ``int64``. Literals of these types have the suffix 'iXX. ``uint`` - the generic `unsigned integer`:idx: type; its size is platform dependent and - has the same size as a pointer. An integer literal with the type - suffix ``'u`` is of this type. + the generic `unsigned integer`:idx: type; its size is platform-dependent and has the same size as a pointer. An integer literal with the type suffix ``'u`` is of this type. uintXX additional unsigned integer types of XX bits use this naming scheme - (example: uint16 is a 16 bit wide unsigned integer). + (example: uint16 is a 16-bit wide unsigned integer). The current implementation supports ``uint8``, ``uint16``, ``uint32``, ``uint64``. Literals of these types have the suffix 'uXX. Unsigned operations all wrap around; they cannot lead to over- or @@ -977,7 +975,7 @@ For further details, see `Convertible relation Subrange types -------------- -A subrange type is a range of values from an ordinal or floating point type (the base +A subrange type is a range of values from an ordinal or floating-point type (the base type). To define a subrange type, one must specify its limiting values -- the lowest and highest value of the type. For example: @@ -988,8 +986,8 @@ lowest and highest value of the type. For example: ``Subrange`` is a subrange of an integer which can only hold the values 0 -to 5. ``PositiveFloat`` defines a subrange of all positive floating point values. -NaN does not belong to any subrange of floating point types. +to 5. ``PositiveFloat`` defines a subrange of all positive floating-point values. +NaN does not belong to any subrange of floating-point types. Assigning any other value to a variable of type ``Subrange`` is a panic (or a static error if it can be determined during semantic analysis). Assignments from the base type to one of its subrange types @@ -999,27 +997,27 @@ A subrange type has the same size as its base type (``int`` in the Subrange example). -Pre-defined floating point types +Pre-defined floating-point types -------------------------------- -The following floating point types are pre-defined: +The following floating-point types are pre-defined: ``float`` - the generic floating point type; its size used to be platform dependent, + the generic floating-point type; its size used to be platform-dependent, but now it is always mapped to ``float64``. This type should be used in general. floatXX - an implementation may define additional floating point types of XX bits using - this naming scheme (example: float64 is a 64 bit wide float). The current + an implementation may define additional floating-point types of XX bits using + this naming scheme (example: float64 is a 64-bit wide float). The current implementation supports ``float32`` and ``float64``. Literals of these types have the suffix 'fXX. Automatic type conversion in expressions with different kinds -of floating point types is performed: See `Convertible relation`_ for further -details. Arithmetic performed on floating point types follows the IEEE -standard. Integer types are not converted to floating point types automatically +of floating-point types is performed: See `Convertible relation`_ for further +details. Arithmetic performed on floating-point types follows the IEEE +standard. Integer types are not converted to floating-point types automatically and vice versa. The IEEE standard defines five types of floating-point exceptions: @@ -1059,7 +1057,7 @@ combination of ``nanChecks`` and ``infChecks`` pragmas. ``floatChecks`` are turned off as default. The only operations that are affected by the ``floatChecks`` pragma are -the ``+``, ``-``, ``*``, ``/`` operators for floating point types. +the ``+``, ``-``, ``*``, ``/`` operators for floating-point types. An implementation should always use the maximum precision available to evaluate floating pointer values during semantic analysis; this means expressions like @@ -1094,9 +1092,9 @@ The size of the bool type is one byte. Character type -------------- The character type is named ``char`` in Nim. Its size is one byte. -Thus it cannot represent an UTF-8 character, but a part of it. +Thus it cannot represent a UTF-8 character, but a part of it. 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. Another reason is that Nim can support ``array[char, int]`` or ``set[char]`` efficiently as many algorithms rely on this feature. The @@ -1144,7 +1142,7 @@ An explicit ordered enum can have *holes*: TokenType = enum a = 2, b = 4, c = 89 # holes are valid -However, it is then not an ordinal anymore, so it is not possible to use these +However, it is then not ordinal anymore, so it is not possible to use these enums as an index type for arrays. The procedures ``inc``, ``dec``, ``succ`` and ``pred`` are not available for them either. @@ -1166,8 +1164,8 @@ As can be seen from the example, it is possible to both specify a field's ordinal value and its string value by using a tuple. It is also possible to only specify one of them. -An enum can be marked with the ``pure`` pragma so that it's fields are -added to a special module specific hidden scope that is only queried +An enum can be marked with the ``pure`` pragma so that its fields are +added to a special module-specific hidden scope that is only queried as the last attempt. Only non-ambiguous symbols are added to this scope. But one can always access these via type qualification written as ``MyEnum.value``: @@ -1254,7 +1252,7 @@ cstring type The ``cstring`` type meaning `compatible string` is the native representation of a string for the compilation backend. For the C backend the ``cstring`` type represents a pointer to a zero-terminated char array -compatible to the type ``char*`` in Ansi C. Its primary purpose lies in easy +compatible with the type ``char*`` in Ansi C. Its primary purpose lies in easy interfacing with C. The index operation ``s[i]`` means the i-th *char* of ``s``; however no bounds checking for ``cstring`` is performed making the index operation unsafe. @@ -1271,7 +1269,7 @@ variadic proc, it is implicitly converted to ``cstring`` too: Even though the conversion is implicit, it is not *safe*: The garbage collector does not consider a ``cstring`` to be a root and may collect the underlying -memory. However in practice this almost never happens as the GC considers +memory. However, in practice, this almost never happens as the GC considers stack roots conservatively. One can use the builtin procs ``GC_ref`` and ``GC_unref`` to keep the string data alive for the rare cases where it does not work. @@ -1288,7 +1286,7 @@ Structured types ---------------- A variable of a structured type can hold multiple values at the same time. Structured types can be nested to unlimited levels. Arrays, sequences, -tuples, objects and sets belong to the structured types. +tuples, objects, and sets belong to the structured types. Array and sequence types ------------------------ @@ -1341,7 +1339,7 @@ The notation ``x[i]`` can be used to access the i-th element of ``x``. Arrays are always bounds checked (statically or at runtime). These checks can be disabled via pragmas or invoking the compiler with the -``--boundChecks:off`` command line switch. +``--boundChecks:off`` command-line switch. An array constructor can have explicit indexes for readability: @@ -1456,7 +1454,7 @@ Unchecked arrays ---------------- The ``UncheckedArray[T]`` type is a special kind of ``array`` where its bounds are not checked. This is often useful to implement customized flexibly sized -arrays. Additionally an unchecked array is translated into a C array of +arrays. Additionally, an unchecked array is translated into a C array of undetermined size: .. code-block:: nim @@ -1526,7 +1524,7 @@ trailing comma: In fact, a trailing comma is allowed for every tuple construction. -The implementation aligns the fields for best access performance. The alignment +The implementation aligns the fields for the best access performance. The alignment is compatible with the way the C compiler does it. For consistency with ``object`` declarations, tuples in a ``type`` section @@ -1540,7 +1538,7 @@ can also be defined with indentation instead of ``[]``: Objects provide many features that tuples do not. Object provide inheritance and the ability to hide fields from other modules. Objects with inheritance enabled -have information about their type at runtime, so that the ``of`` operator can be +have information about their type at runtime so that the ``of`` operator can be used to determine the object's type. The ``of`` operator is similar to the ``instanceof`` operator in Java. @@ -1592,8 +1590,8 @@ For a ``ref object`` type ``system.new`` is invoked implicitly. Object variants --------------- -Often an object hierarchy is overkill in certain situations where simple variant -types are needed. Object variants are tagged unions discriminated via a +Often an object hierarchy is an overkill in certain situations where simple variant +types are needed. Object variants are tagged unions discriminated via an enumerated type used for runtime type flexibility, mirroring the concepts of *sum types* and *algebraic data types (ADTs)* as found in other languages. @@ -1638,14 +1636,14 @@ An example: # valid: does not change the active object branch: x.kind = nkSub -As can been seen from the example, an advantage to an object hierarchy is that +As can be seen from the example, an advantage to an object hierarchy is that no casting between different object types is needed. Yet, access to invalid object fields raises an exception. The syntax of ``case`` in an object declaration follows closely the syntax of the ``case`` statement: The branches in a ``case`` section may be indented too. -In the example the ``kind`` field is called the `discriminator`:idx:\: For +In the example, the ``kind`` field is called the `discriminator`:idx:\: For safety its address cannot be taken and assignments to it are restricted: The new value must not lead to a change of the active object branch. Also, when the fields of a particular branch are specified during object construction, the @@ -1708,16 +1706,16 @@ point to and modify the same location in memory (also called `aliasing`:idx:). Nim distinguishes between `traced`:idx: and `untraced`:idx: references. Untraced references are also called *pointers*. Traced references point to -objects of a garbage collected heap, untraced references point to -manually allocated objects or to objects somewhere else in memory. Thus -untraced references are *unsafe*. However for certain low-level operations +objects of a garbage-collected heap, untraced references point to +manually allocated objects or objects somewhere else in memory. Thus +untraced references are *unsafe*. However, for certain low-level operations (accessing the hardware) untraced references are unavoidable. Traced references are declared with the **ref** keyword, untraced references are declared with the **ptr** keyword. In general, a `ptr T` is implicitly convertible to the `pointer` type. -An empty subscript ``[]`` notation can be used to derefer a reference, +An empty subscript ``[]`` notation can be used to de-refer a reference, the ``addr`` procedure returns the address of an item. An address is always an untraced reference. Thus the usage of ``addr`` is an *unsafe* feature. @@ -1807,7 +1805,7 @@ Mixing GC'ed memory with ``ptr`` -------------------------------- Special care has to be taken if an untraced object contains traced objects like -traced references, strings or sequences: in order to free everything properly, +traced references, strings, or sequences: in order to free everything properly, the built-in procedure ``reset`` has to be called before freeing the untraced memory manually: @@ -1828,8 +1826,7 @@ memory manually: dealloc(d) Without the ``reset`` call the memory allocated for the ``d.s`` string would -never be freed. The example also demonstrates two important features for low -level programming: the ``sizeof`` proc returns the size of a type or value +never be freed. The example also demonstrates two important features for low-level programming: the ``sizeof`` proc returns the size of a type or value in bytes. The ``cast`` operator can circumvent the type system: the compiler is forced to treat the result of the ``alloc0`` call (which returns an untyped pointer) as if it would have the type ``ptr Data``. Casting should only be @@ -1838,8 +1835,8 @@ mysterious crashes. **Note**: The example only works because the memory is initialized to zero (``alloc0`` instead of ``alloc`` does this): ``d.s`` is thus initialized to -binary zero which the string assignment can handle. One needs to know low level -details like this when mixing garbage collected data with unmanaged memory. +binary zero which the string assignment can handle. One needs to know low-level +details like this when mixing garbage-collected data with unmanaged memory. .. XXX finalizers for traced objects @@ -1948,7 +1945,7 @@ accesses its environment. If it does so, it has the calling convention Distinct type ------------- -A ``distinct`` type is new type derived from a `base type`:idx: that is +A ``distinct`` type is a new type derived from a `base type`:idx: that is incompatible with its base type. In particular, it is an essential property of a distinct type that it **does not** imply a subtype relation between it and its base type. Explicit type conversions from a distinct type to its @@ -1958,7 +1955,7 @@ reverse operation. A distinct type is an ordinal type if its base type is an ordinal type. -Modelling currencies +Modeling currencies ~~~~~~~~~~~~~~~~~~~~ A distinct type can be used to model different physical `units`:idx: with a @@ -2002,7 +1999,7 @@ number without unit; and the same holds for division: This quickly gets tedious. The implementations are trivial and the compiler should not generate all this code only to optimize it away later - after all ``+`` for dollars should produce the same binary code as ``+`` for ints. -The pragma `borrow`:idx: has been designed to solve this problem; in principle +The pragma `borrow`:idx: has been designed to solve this problem; in principle, it generates the above trivial implementations: .. code-block:: nim @@ -2067,14 +2064,14 @@ certain builtin operations to be lifted: bb.a = 90 bb.s = "abc" -Currently only the dot accessor can be borrowed in this way. +Currently, only the dot accessor can be borrowed in this way. Avoiding SQL injection attacks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An SQL statement that is passed from Nim to an SQL database might be -modelled as a string. However, using string templates and filling in the +modeled as a string. However, using string templates and filling in the values is vulnerable to the famous `SQL injection attack`:idx:\: .. code-block:: nim @@ -2152,7 +2149,7 @@ Is the same as: .. code-block:: nim proc foo[T1, T2](a: T1, b: T2) = discard -However later versions of the language might change this to mean "infer the +However, later versions of the language might change this to mean "infer the parameters' types from the body". Then the above ``foo`` would be rejected as the parameters' types can not be inferred from an empty ``discard`` statement. @@ -2375,8 +2372,8 @@ of the argument. 1. Exact match: ``a`` and ``f`` are of the same type. 2. Literal match: ``a`` is an integer literal of value ``v`` and ``f`` is a signed or unsigned integer type and ``v`` is in ``f``'s - range. Or: ``a`` is a floating point literal of value ``v`` - and ``f`` is a floating point type and ``v`` is in ``f``'s + range. Or: ``a`` is a floating-point literal of value ``v`` + and ``f`` is a floating-point type and ``v`` is in ``f``'s range. 3. Generic match: ``f`` is a generic type and ``a`` matches, for instance ``a`` is ``int`` and ``f`` is a generic (constrained) parameter @@ -2384,7 +2381,7 @@ of the argument. 4. Subrange or subtype match: ``a`` is a ``range[T]`` and ``T`` matches ``f`` exactly. Or: ``a`` is a subtype of ``f``. 5. Integral conversion match: ``a`` is convertible to ``f`` and ``f`` and ``a`` - is some integer or floating point type. + is some integer or floating-point type. 6. Conversion match: ``a`` is convertible to ``f``, possibly via a user defined ``converter``. @@ -2507,7 +2504,7 @@ Lazy type resolution for untyped lookups and no type checking have been performed. Since templates and macros that are not declared as ``immediate`` participate -in overloading resolution it's essential to have a way to pass unresolved +in overloading resolution, it's essential to have a way to pass unresolved expressions to a template or macro. This is what the meta-type ``untyped`` accomplishes: @@ -2549,7 +2546,7 @@ statements. Statements are separated into `simple statements`:idx: and `complex statements`:idx:. Simple statements are statements that cannot contain other statements like -assignments, calls or the ``return`` statement; complex statements can +assignments, calls, or the ``return`` statement; complex statements can contain other statements. To avoid the `dangling else problem`:idx:, complex statements always have to be indented. The details can be found in the grammar. @@ -2559,7 +2556,7 @@ Statement list expression Statements can also occur in an expression context that looks like ``(stmt1; stmt2; ...; ex)``. This is called -an statement list expression or ``(;)``. The type +a statement list expression or ``(;)``. The type of ``(stmt1; stmt2; ...; ex)`` is the type of ``ex``. All the other statements must be of type ``void``. (One can use ``discard`` to produce a ``void`` type.) ``(;)`` does not introduce a new scope. @@ -2635,7 +2632,7 @@ Var statement ------------- Var statements declare new local and global variables and -initialize them. A comma separated list of variables can be used to specify +initialize them. A comma-separated list of variables can be used to specify variables of the same type: .. code-block:: nim @@ -2684,7 +2681,7 @@ If a proc is annotated with the ``noinit`` pragma this refers to its implicit The implicit initialization can be also prevented by the `requiresInit`:idx: type pragma. The compiler requires an explicit initialization for the object -and all of its fields. However it does a `control flow analysis`:idx: to prove +and all of its fields. However, it does a `control flow analysis`:idx: to prove the variable has been initialized and does not rely on syntactic properties: .. code-block:: nim @@ -2710,7 +2707,7 @@ statement, except that the keyword ``var`` is replaced by the keyword ``let``. Let variables are not l-values and can thus not be passed to ``var`` parameters nor can their address be taken. They cannot be assigned new values. -For let variables the same pragmas are available as for ordinary variables. +For let variables, the same pragmas are available as for ordinary variables. As ``let`` statements are immutable after creation they need to define a value when they are declared. The only exception to this is if the ``{.importc.}`` @@ -2837,7 +2834,7 @@ ordinal types. "All possible values" of ``expr`` are determined by ``expr``'s type. To suppress the static error an ``else`` part with an empty ``discard`` statement should be used. -For non ordinal types it is not possible to list every possible value and so +For non-ordinal types, it is not possible to list every possible value and so these always require an ``else`` part. Because case statements are checked for exhaustiveness during semantic analysis, @@ -2928,8 +2925,8 @@ within ``object`` definitions. When nimvm statement -------------------- -``nimvm`` is a special symbol, that may be used as expression of ``when nimvm`` -statement to differentiate execution path between compile time and the +``nimvm`` is a special symbol, that may be used as an expression of ``when nimvm`` +statement to differentiate execution path between compile-time and the executable. Example: @@ -2995,7 +2992,7 @@ Example: The ``yield`` statement is used instead of the ``return`` statement in iterators. It is only valid in iterators. Execution is returned to the body of the for loop that called the iterator. Yield does not end the iteration -process, but execution is passed back to the iterator if the next iteration +process, but the execution is passed back to the iterator if the next iteration starts. See the section about iterators (`Iterators and the for statement`_) for further information. @@ -3155,7 +3152,7 @@ name ``c`` should default to type ``Context``, ``n`` should default to The ``using`` section uses the same indentation based grouping syntax as a ``var`` or ``let`` section. -Note that ``using`` is not applied for ``template`` since untyped template +Note that ``using`` is not applied for ``template`` since the untyped template parameters default to the type ``system.untyped``. Mixing parameters that should use the ``using`` declaration with parameters @@ -3202,9 +3199,9 @@ Block expression ---------------- A `block expression` is almost like a block statement, but it is an expression -that uses last expression under the block as the value. +that uses the last expression under the block as the value. It is similar to the statement list expression, but the statement list expression -does not open new block scope. +does not open a new block scope. .. code-block:: nim let a = block: @@ -3236,7 +3233,7 @@ has lots of advantages: can easily put it into the executable's data section just like it can for arrays and the generated data section requires a minimal amount of memory. -* Every table implementation is treated equal syntactically. +* Every table implementation is treated equally syntactically. * Apart from the minimal syntactic sugar the language core does not need to know about tables. @@ -3251,9 +3248,9 @@ results in an exception (if it cannot be determined statically). Ordinary procs are often preferred over type conversions in Nim: For instance, ``$`` is the ``toString`` operator by convention and ``toFloat`` and ``toInt`` -can be used to convert from floating point to integer or vice versa. +can be used to convert from floating-point to integer or vice versa. -A type conversion can also be used to disambiguate overloaded routines: +Type conversion can also be used to disambiguate overloaded routines: .. code-block:: nim @@ -3347,7 +3344,7 @@ declaration consists of an identifier, zero or more formal parameters, a return value type and a block of code. Formal parameters are declared as a list of identifiers separated by either comma or semicolon. A parameter is given a type by ``: typename``. The type applies to all parameters immediately before it, -until either the beginning of the parameter list, a semicolon separator or an +until either the beginning of the parameter list, a semicolon separator, or an already typed parameter, is reached. The semicolon can be used to make separation of types and subsequent identifiers more distinct. @@ -3460,7 +3457,7 @@ current module: Method call syntax ------------------ -For object oriented programming, the syntax ``obj.method(args)`` can be used +For object-oriented programming, the syntax ``obj.method(args)`` can be used instead of ``method(obj, args)``. The parentheses can be omitted if there are no remaining arguments: ``obj.len`` (instead of ``len(obj)``). @@ -3494,7 +3491,7 @@ Properties ---------- Nim has no need for *get-properties*: Ordinary get-procedures that are called with the *method call syntax* achieve the same. But setting a value is -different; for this a special setter syntax is needed: +different; for this, a special setter syntax is needed: .. code-block:: nim # Module asocket @@ -3566,8 +3563,8 @@ more argument in this case: The command invocation syntax also can't have complex expressions as arguments. For example: (`anonymous procs <#procedures-anonymous-procs>`_), ``if``, -``case`` or ``try``. Function calls with no arguments still needs () to -distinguish between a call and the function itself as a first class value. +``case`` or ``try``. Function calls with no arguments still need () to +distinguish between a call and the function itself as a first-class value. Closures @@ -3603,7 +3600,7 @@ procedures: cmp(x.len, y.len)) -Procs as expressions can appear both as nested procs and inside top level +Procs as expressions can appear both as nested procs and inside top-level executable code. The `sugar `_ module contains the `=>` macro which enables a more succinct syntax for anonymous procedures resembling lambdas as they are in languages like JavaScript, C#, etc. @@ -3627,7 +3624,7 @@ Is short for: Nonoverloadable builtins ------------------------ -The following builtin procs cannot be overloaded for reasons of implementation +The following built-in procs cannot be overloaded for reasons of implementation simplicity (they require specialized semantic checking):: declared, defined, definedInScope, compiles, sizeof, @@ -3636,7 +3633,7 @@ simplicity (they require specialized semantic checking):: Thus they act more like keywords than like ordinary identifiers; unlike a keyword however, a redefinition may `shadow`:idx: the definition in the ``system`` module. From this list the following should not be written in dot -notation ``x.f`` since ``x`` cannot be type checked before it gets passed +notation ``x.f`` since ``x`` cannot be type-checked before it gets passed to ``f``:: declared, defined, definedInScope, compiles, getAst, astToStr @@ -3703,7 +3700,7 @@ free to pass arguments by reference if it considers it can speed up execution. Var return type --------------- -A proc, converter or iterator may return a ``var`` type which means that the +A proc, converter, or iterator may return a ``var`` type which means that the returned value is an l-value and can be modified by the caller: .. code-block:: nim @@ -3994,7 +3991,7 @@ the rewriting step, so that all overloads of ``items``/``pairs`` are taken into account. -First class iterators +First-class iterators --------------------- There are 2 kinds of iterators in Nim: *inline* and *closure* iterators. @@ -4009,7 +4006,7 @@ to avoid code bloat. Inline iterators are second class citizens; They can be passed as parameters only to other inlining code facilities like -templates, macros and other inline iterators. +templates, macros, and other inline iterators. In contrast to that, a `closure iterator`:idx: can be passed around more freely: @@ -4284,7 +4281,7 @@ above, ``IOError``), one must convert it explicitly: # "e" is now of the proper type However, this is seldom needed. The most common case is to extract an -error message from ``e``, and for such situations it is enough to use +error message from ``e``, and for such situations, it is enough to use ``getCurrentExceptionMsg``: .. code-block:: nim @@ -4339,7 +4336,7 @@ Is rewritten to: finally: close(f) -Top level ``defer`` statements are not supported +Top-level ``defer`` statements are not supported since it's unclear what such a statement should refer to. @@ -4474,9 +4471,7 @@ possibly raised exceptions; the algorithm operates on ``p``'s call graph: 1. Every indirect call via some proc type ``T`` is assumed to raise ``system.Exception`` (the base type of the exception hierarchy) and thus any exception unless ``T`` has an explicit ``raises`` list. - However if the call is of the form ``f(...)`` where ``f`` is a parameter - of the currently analysed routine it is ignored. The call is optimistically - assumed to have no effect. Rule 2 compensates for this case. + However, if the call is of the form ``f(...)`` where ``f`` is a parameter of the currently analyzed routine it is ignored. The call is optimistically assumed to have no effect. Rule 2 compensates for this case. 2. Every expression of some proc type within a call that is not a call itself (and not nil) is assumed to be called indirectly somehow and thus its raises list is added to ``p``'s raises list. @@ -4579,10 +4574,10 @@ Generics ======== Generics are Nim's means to parametrize procs, iterators or types with -`type parameters`:idx:. Depending on context, the brackets are used either to -introduce type parameters or to instantiate a generic proc, iterator or type. +`type parameters`:idx:. Depending on the context, the brackets are used either to +introduce type parameters or to instantiate a generic proc, iterator, or type. -The following example shows a generic binary tree can be modelled: +The following example shows a generic binary tree can be modeled: .. code-block:: nim :test: "nim c $1" @@ -4705,7 +4700,7 @@ more complex type classes: Whilst the syntax of type classes appears to resemble that of ADTs/algebraic data types in ML-like languages, it should be understood that type classes are static constraints to be enforced at type instantiations. Type classes are not really -types in themselves, but are instead a system of providing generic "checks" that +types in themselves but are instead a system of providing generic "checks" that ultimately *resolve* to some singular type. Type classes do not allow for runtime type dynamism, unlike object variants or methods. @@ -4742,11 +4737,11 @@ A type class can be used directly as the parameter's type. echo key, " = ", value -Procedures utilizing type classes in such manner are considered to be +Procedures utilizing type classes in such a manner are considered to be `implicitly generic`:idx:. They will be instantiated once for each unique combination of param types used within the program. -By default, during overload resolution each named type class will bind to +By default, during overload resolution, each named type class will bind to exactly one concrete type. We call such type classes `bind once`:idx: types. Here is an example taken directly from the system module to illustrate this: @@ -4899,7 +4894,7 @@ at definition and the context at instantiation are considered: echo a == b # works! -In the example the generic ``==`` for tuples (as defined in the system module) +In the example, the generic ``==`` for tuples (as defined in the system module) uses the ``==`` operators of the tuple's components. However, the ``==`` for the ``Index`` type is defined *after* the ``==`` for tuples; yet the example compiles as the instantiation takes the currently defined symbols into account @@ -5008,7 +5003,7 @@ example *undeclared* identifiers can be passed to the template: template declareInt(x: typed) = var x: int - declareInt(x) # invalid, because x has not been declared and so has no type + declareInt(x) # invalid, because x has not been declared and so it has no type A template where every parameter is ``untyped`` is called an `immediate`:idx: template. For historical reasons templates can be explicitly annotated with @@ -5344,7 +5339,7 @@ A macro is a special function that is executed at compile time. Normally the input for a macro is an abstract syntax tree (AST) of the code that is passed to it. The macro can then do transformations on it and return the transformed AST. This can be used to -add custom language features and implement `domain specific languages`:idx:. +add custom language features and implement `domain-specific languages`:idx:. Macro invocation is a case where semantic analysis does **not** entirely proceed top to bottom and left to right. Instead, semantic analysis happens at least @@ -5608,11 +5603,11 @@ possible type mismatch error. typedesc[T] ----------- -In many contexts, Nim allows to treat the names of types as regular -values. These values exists only during the compilation phase, but since +In many contexts, Nim treats the names of types as regular +values. These values exist only during the compilation phase, but since all values must have a type, ``typedesc`` is considered their special type. -``typedesc`` acts like a generic type. For instance, the type of the symbol +``typedesc`` acts as a generic type. For instance, the type of the symbol ``int`` is ``typedesc[int]``. Just like with regular generic types, when the generic param is omitted, ``typedesc`` denotes the type class of all types. As a syntactic convenience, one can also use ``typedesc`` as a modifier. @@ -5649,7 +5644,7 @@ Once bound, type params can appear in the rest of the proc signature: Overload resolution can be further influenced by constraining the set -of types that will match the type param. This works in practice to +of types that will match the type param. This works in practice by attaching attributes to types via templates. The constraint can be a concrete type or a type class. @@ -5705,7 +5700,7 @@ operator): If ``typeof`` is used to determine the result type of a proc/iterator/converter call ``c(X)`` (where ``X`` stands for a possibly empty list of arguments), the -interpretation where ``c`` is an iterator is preferred over the +interpretation, where ``c`` is an iterator, is preferred over the other interpretations, but this behavior can be changed by passing ``typeOfProc`` as the second argument to ``typeof``: @@ -5783,7 +5778,7 @@ imported: It is not checked that the ``except`` list is really exported from the module. -This feature allows to compile against an older version of the module that +This feature allows us to compile against an older version of the module that does not export these identifiers. The ``import`` statement is only allowed at the top level. @@ -5836,7 +5831,7 @@ and so one **cannot** do: import lib/pure/strutils echo lib/pure/strutils.toUpperAscii("abc") -Likewise the following does not make sense as the name is ``strutils`` already: +Likewise, the following does not make sense as the name is ``strutils`` already: .. code-block:: nim import lib/pure/strutils as strutils @@ -5858,7 +5853,7 @@ name is not a valid Nim identifier it needs to be a string literal: Pseudo import/include paths ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A directory can also be a so called "pseudo directory". They can be used to +A directory can also be a so-called "pseudo directory". They can be used to avoid ambiguity when there are multiple modules with the same path. There are two pseudo directories: @@ -5875,7 +5870,7 @@ library locations*. In other words, it is the opposite of ``std``. From import statement ~~~~~~~~~~~~~~~~~~~~~ -After the ``from`` statement a module name follows followed by +After the ``from`` statement, a module name follows followed by an ``import`` to list the symbols one likes to use without explicit full qualification: @@ -5964,7 +5959,7 @@ the end of the module. Identifiers from indirectly dependent modules are *not* available. The `system`:idx: module is automatically imported in every module. If a module imports an identifier by two different modules, each occurrence of -the identifier has to be qualified, unless it is an overloaded procedure or +the identifier has to be qualified unless it is an overloaded procedure or iterator in which case the overloading resolution takes place: .. code-block:: nim @@ -6121,7 +6116,7 @@ Or if we directly use a ref object: left, right: Node data: string -In the example a tree structure is declared with the ``Node`` type. Note that +In the example, a tree structure is declared with the ``Node`` type. Note that the type definition is recursive and the GC has to assume that objects of this type may form a cyclic graph. The ``acyclic`` pragma passes the information that this cannot happen to the GC. If the programmer uses the @@ -6182,7 +6177,7 @@ assembler statements. error pragma ------------ The ``error`` pragma is used to make the compiler output an error message -with the given content. Compilation does not necessarily abort after an error +with the given content. The compilation does not necessarily abort after an error though. The ``error`` pragma can also be used to @@ -6198,7 +6193,7 @@ operation is valid due to overloading and type conversions: fatal pragma ------------ The ``fatal`` pragma is used to make the compiler output an error message -with the given content. In contrast to the ``error`` pragma, compilation +with the given content. In contrast to the ``error`` pragma, the compilation is guaranteed to be aborted by this pragma. Example: .. code-block:: nim @@ -6218,7 +6213,7 @@ the given content. Compilation continues after the hint. line pragma ----------- The ``line`` pragma can be used to affect line information of the annotated -statement as seen in stack backtraces: +statement, as seen in stack backtraces: .. code-block:: nim @@ -6251,9 +6246,9 @@ statement: In the example, the case branches ``0`` and ``1`` are much more common than the other cases. Therefore the generated assembler code should test for these -values first, so that the CPU's branch predictor has a good chance to succeed +values first so that the CPU's branch predictor has a good chance to succeed (avoiding an expensive CPU pipeline stall). The other cases might be put into a -jump table for O(1) overhead, but at the cost of a (very likely) pipeline +jump table for O(1) overhead but at the cost of a (very likely) pipeline stall. The ``linearScanEnd`` pragma should be put into the last branch that should be @@ -6383,7 +6378,7 @@ but are used to override the settings temporarily. Example: proc sample(): bool = true {.pop.} -For third party pragmas it depends on its implementation, but uses the same syntax. +For third party pragmas, it depends on its implementation but uses the same syntax. register pragma @@ -6445,7 +6440,7 @@ is particularly useful when the symbol was generated by a macro: implementArithOps(int) echoAdd 3, 5 -``used`` can also be used as a top level statement to mark a module as "used". +``used`` can also be used as a top-level statement to mark a module as "used". This prevents the "Unused import" warning: .. code-block:: nim @@ -6462,9 +6457,9 @@ experimental pragma ------------------- The ``experimental`` pragma enables experimental language features. Depending -on the concrete feature this means that the feature is either considered +on the concrete feature, this means that the feature is either considered too unstable for an otherwise stable release or that the future of the feature -is uncertain (it may be removed any time). +is uncertain (it may be removed at any time). Example: @@ -6483,9 +6478,9 @@ Example: useParallel() -As a top level statement, the experimental pragma enables a feature for the +As a top-level statement, the experimental pragma enables a feature for the rest of the module it's enabled in. This is problematic for macro and generic -instantiations that cross a module scope. Currently these usages have to be +instantiations that cross a module scope. Currently, these usages have to be put into a ``.push/pop`` environment: .. code-block:: nim @@ -6539,7 +6534,7 @@ The `align`:idx: pragma is for variables and object field members. It modifies the alignment requirement of the entity being declared. The argument must be a constant power of 2. Valid non-zero alignments that are weaker than other align pragmas on the same -declaration are ignored. Alignments that are weaker that the +declaration are ignored. Alignments that are weaker than the alignment requirement of the type are ignored. .. code-block:: Nim @@ -6562,7 +6557,7 @@ alignment requirement of the type are ignored. main() -This pragma has no effect for the JS backend. +This pragma has no effect on the JS backend. Volatile pragma @@ -6595,7 +6590,7 @@ Header pragma ------------- The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be applied to almost any symbol and specifies that it should not be declared -and instead the generated code should contain an ``#include``: +and instead, the generated code should contain an ``#include``: .. code-block:: Nim type @@ -6630,7 +6625,7 @@ with the project: {.compile: "myfile.cpp".} **Note**: Nim computes a SHA1 checksum and only recompiles the file if it -has changed. One can use the ``-f`` command line option to force recompilation +has changed. One can use the ``-f`` command-line option to force the recompilation of the file. Since 1.4 the `compile` pragma is also available with this syntax: @@ -6653,7 +6648,7 @@ The ``link`` pragma can be used to link an additional file with the project: PassC pragma ------------ The ``passc`` pragma can be used to pass additional parameters to the C -compiler like one would using the commandline switch ``--passc``: +compiler like one would using the command-line switch ``--passc``: .. code-block:: Nim {.passc: "-Wall -Werror".} @@ -6681,7 +6676,7 @@ the pragma resides in: PassL pragma ------------ The ``passL`` pragma can be used to pass additional parameters to the linker -like one would using the commandline switch ``--passL``: +like one would be using the command-line switch ``--passL``: .. code-block:: Nim {.passL: "-lSDLmain -lSDL".} @@ -6728,7 +6723,7 @@ Example: void fun(){} """.} -For backwards compatibility, if the argument to the ``emit`` statement +For backward compatibility, if the argument to the ``emit`` statement is a single string literal, Nim symbols can be referred to via backticks. This usage is however deprecated. @@ -6828,8 +6823,7 @@ language for maximum flexibility: - A hash ``#`` symbol is replaced by the first or next argument. - A dot following the hash ``#.`` indicates that the call should use C++'s dot or arrow notation. -- An at symbol ``@`` is replaced by the remaining arguments, separated by - commas. +- An at symbol ``@`` is replaced by the remaining arguments, separated by commas. For example: @@ -6843,7 +6837,7 @@ Produces: .. code-block:: C x->CppMethod(1, 2, 3) -As a special rule to keep backwards compatibility with older versions of the +As a special rule to keep backward compatibility with older versions of the ``importcpp`` pragma, if there is no special pattern character (any of ``# ' @``) at all, C++'s dot or arrow notation is assumed, so the above example can also be written as: @@ -6862,7 +6856,7 @@ capabilities: - An apostrophe ``'`` followed by an integer ``i`` in the range 0..9 is replaced by the i'th parameter *type*. The 0th position is the result type. This can be used to pass types to C++ function templates. Between - the ``'`` and the digit an asterisk can be used to get to the base type + the ``'`` and the digit, an asterisk can be used to get to the base type of the type. (So it "takes away a star" from the type; ``T*`` becomes ``T``.) Two stars can be used to get to the element type of the element type etc. @@ -6929,7 +6923,7 @@ Wrapping destructors Since Nim generates C++ directly, any destructor is called implicitly by the C++ compiler at the scope exits. This means that often one can get away with -not wrapping the destructor at all! However when it needs to be invoked +not wrapping the destructor at all! However, when it needs to be invoked explicitly, it needs to be wrapped. The pattern language provides everything that is required: @@ -7046,7 +7040,7 @@ The ``codegenDecl`` pragma can be used to directly influence Nim's code generator. It receives a format string that determines how the variable or proc is declared in the generated code. -For variables $1 in the format string represents the type of the variable +For variables, $1 in the format string represents the type of the variable and $2 is the name of the variable. The following Nim code: @@ -7087,7 +7081,7 @@ debugging: # ... complex code here that produces crashes ... -compile time define pragmas +compile-time define pragmas --------------------------- The pragmas listed here can be used to optionally accept values from @@ -7112,7 +7106,7 @@ pragma description nim c -d:FooBar=42 foobar.nim In the above example, providing the -d flag causes the symbol -``FooBar`` to be overwritten at compile time, printing out 42. If the +``FooBar`` to be overwritten at compile-time, printing out 42. If the ``-d:FooBar=42`` were to be omitted, the default value of 5 would be used. To see if a value was provided, `defined(FooBar)` can be used. @@ -7125,9 +7119,8 @@ User-defined pragmas pragma pragma ------------- -The ``pragma`` pragma can be used to declare user defined pragmas. This is -useful because Nim's templates and macros do not affect pragmas. User -defined pragmas are in a different module-wide scope than all other symbols. +The ``pragma`` pragma can be used to declare user-defined pragmas. This is +useful because Nim's templates and macros do not affect pragmas. User-defined pragmas are in a different module-wide scope than all other symbols. They cannot be imported from a module. Example: @@ -7141,14 +7134,14 @@ Example: proc p*(a, b: int): int {.rtl.} = result = a+b -In the example a new pragma named ``rtl`` is introduced that either imports +In the example, a new pragma named ``rtl`` is introduced that either imports a symbol from a dynamic library or exports the symbol for dynamic library generation. Custom annotations ------------------ -It is possible to define custom typed pragmas. Custom pragmas do not effect +It is possible to define custom typed pragmas. Custom pragmas do not affect code generation directly, but their presence can be detected by macros. Custom pragmas are defined using templates annotated with pragma ``pragma``: @@ -7178,7 +7171,7 @@ Consider stylized example of possible Object Relation Mapping (ORM) implementati write_access: bool admin_acess: bool -In this example custom pragmas are used to describe how Nim objects are +In this example, custom pragmas are used to describe how Nim objects are mapped to the schema of the relational database. Custom pragmas can have zero or more arguments. In order to pass multiple arguments use one of template call syntaxes. All arguments are typed and follow standard @@ -7216,7 +7209,7 @@ Macro pragmas ------------- All macros and templates can also be used as pragmas. They can be attached -to routines (procs, iterators, etc), type names or type expressions. The +to routines (procs, iterators, etc), type names, or type expressions. The compiler will perform the following simple syntactic transformations: .. code-block:: nim @@ -7299,7 +7292,7 @@ is not set to C, other pragmas are available: .. code-block:: Nim proc p(s: cstring) {.importc: "prefix$1".} -In the example the external name of ``p`` is set to ``prefixp``. Only ``$1`` +In the example, the external name of ``p`` is set to ``prefixp``. Only ``$1`` is available and a literal dollar sign must be written as ``$$``. @@ -7339,7 +7332,7 @@ mangling. The string literal passed to ``extern`` can be a format string: proc p(s: string) {.extern: "prefix$1".} = echo s -In the example the external name of ``p`` is set to ``prefixp``. Only ``$1`` +In the example, the external name of ``p`` is set to ``prefixp``. Only ``$1`` is available and a literal dollar sign must be written as ``$$``. @@ -7430,7 +7423,7 @@ At runtime the dynamic library is searched for (in this order):: libtcl8.3.so.1 libtcl8.3.so.0 -The ``dynlib`` pragma supports not only constant strings as argument but also +The ``dynlib`` pragma supports not only constant strings as an argument but also string expressions in general: .. code-block:: nim @@ -7452,7 +7445,7 @@ strings, because they are precompiled. because of order of initialization problems. **Note**: A ``dynlib`` import can be overridden with -the ``--dynlibOverride:name`` command line option. The Compiler User Guide +the ``--dynlibOverride:name`` command-line option. The Compiler User Guide contains further information. @@ -7467,23 +7460,23 @@ conjunction with the ``exportc`` pragma: proc exportme(): int {.cdecl, exportc, dynlib.} This is only useful if the program is compiled as a dynamic library via the -``--app:lib`` command line option. +``--app:lib`` command-line option. Threads ======= -To enable thread support the ``--threads:on`` command line switch needs to +To enable thread support the ``--threads:on`` command-line switch needs to be used. The ``system`` module then contains several threading primitives. See the `threads `_ and `channels `_ modules -for the low level thread API. There are also high level parallelism constructs +for the low-level thread API. There are also high-level parallelism constructs available. See `spawn `_ for further details. Nim's memory model for threads is quite different than that of other common programming languages (C, Pascal, Java): Each thread has its own (garbage -collected) heap and sharing of memory is restricted to global variables. This +collected) heap, and sharing of memory is restricted to global variables. This helps to prevent race conditions. GC efficiency is improved quite a lot, because the GC never has to stop other threads and see what they reference. @@ -7495,7 +7488,7 @@ A proc that is executed as a new thread of execution should be marked by the ``thread`` pragma for reasons of readability. The compiler checks for violations of the `no heap sharing restriction`:idx:\: This restriction implies that it is invalid to construct a data structure that consists of memory -allocated from different (thread local) heaps. +allocated from different (thread-local) heaps. A thread proc is passed to ``createThread`` or ``spawn`` and invoked indirectly; so the ``thread`` pragma implies ``procvar``. @@ -7516,7 +7509,7 @@ any of its parameters contain a ``ref`` or ``closure`` type. This enforces the *no heap sharing restriction*. Routines that are imported from C are always assumed to be ``gcsafe``. -To disable the GC-safety checking the ``--threadAnalysis:off`` command line +To disable the GC-safety checking the ``--threadAnalysis:off`` command-line switch can be used. This is a temporary workaround to ease the porting effort from old code to the new threading model. @@ -7549,8 +7542,8 @@ of the ``global`` pragma. .. code-block:: nim var checkpoints* {.threadvar.}: seq[string] -Due to implementation restrictions thread local variables cannot be -initialized within the ``var`` section. (Every thread local variable needs to +Due to implementation restrictions thread-local variables cannot be +initialized within the ``var`` section. (Every thread-local variable needs to be replicated at thread creation.) diff --git a/doc/manual/var_t_return.rst b/doc/manual/var_t_return.rst index 2235d5aa43308..c6de8cf7ce3e3 100644 --- a/doc/manual/var_t_return.rst +++ b/doc/manual/var_t_return.rst @@ -17,4 +17,4 @@ then it has to be derived from the routine's first parameter: In other words, the lifetime of what ``result`` points to is attached to the lifetime of the first parameter and that is enough knowledge to verify -memory safety at the callsite. +memory safety at the call site. diff --git a/doc/nimc.rst b/doc/nimc.rst index 9a698312b25de..57255a31fc163 100644 --- a/doc/nimc.rst +++ b/doc/nimc.rst @@ -26,9 +26,9 @@ Nim is free software; it is licensed under the Compiler Usage ============== -Command line switches +Command-line switches --------------------- -Basic command line switches are: +Basic command-line switches are: Usage: @@ -36,7 +36,7 @@ Usage: ---- -Advanced command line switches are: +Advanced command-line switches are: .. include:: advopt.txt @@ -62,7 +62,7 @@ SmallLshouldNotBeUsed The letter 'l' should not be used as an identifier. EachIdentIsTuple The code contains a confusing ``var`` declaration. -User Some user defined warning. +User Some user-defined warning. ========================== ============================================ @@ -118,7 +118,7 @@ Level Description `_. This is the default level. 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 `_ if any filter was used during compilation. 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 source code with the `when statement `_ and @@ -139,14 +139,14 @@ enabled for better performance. Another common use is the ``-d:ssl`` switch to activate SSL sockets. Additionally, you may pass a value along with the symbol: ``-d:x=y`` -which may be used in conjunction with the `compile time define -pragmas`_ +which may be used in conjunction with the `compile-time define +pragmas`_ 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. -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. @@ -154,7 +154,7 @@ Configuration files ------------------- **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 @@ -162,12 +162,12 @@ directories (in this order; later files overwrite previous settings): 1) ``$nim/config/nim.cfg``, ``/etc/nim/nim.cfg`` (UNIX) or ``\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. -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. -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. +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. +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 `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. 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. -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 -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 @@ -245,7 +245,7 @@ To use the ``CC`` environment variable, use ``nim c --cc:env myfile.nim``. To us since Nim version 1.4. -Cross compilation +Cross-compilation ================= 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.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 @@ -284,15 +284,15 @@ The MinGW-w64 toolchain can be installed as follows:: 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 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 `_ 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. 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 you need a small Java stub that calls out to a native library written in Nim using the `NDK `_. You can also use -`native-acitivty `_ -to have the Java stub be auto generated for you. +`native-activity `_ +to have the Java stub be auto-generated for you. 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 @@ -323,10 +323,10 @@ of your program. 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 use LLVM and can be compiled into object files linked together with C, C++ 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 would need to define `main` that calls ``autoreleasepool`` and ``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 -initialize Nim's garbage collector and to run the top level statements +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 of your program. .. 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. -Cross compilation for Nintendo Switch +Cross-compilation for Nintendo Switch ===================================== 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 `_ or `here for Windows `_. -For example, with the above mentioned config:: +For example, with the above-mentioned config:: nim c --os:nintendoswitch switchhomebrew.nim @@ -479,8 +479,7 @@ debugging with GDB. StackTrace option ----------------- 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 -uncaught exception is raised. +ensure that proper stack traces are given if the program crashes or some uncaught exception is raised. LineTrace option @@ -509,8 +508,8 @@ Backend language options 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 -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 +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 can be read in the `Nim Backend Integration document `_. @@ -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 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. Nim for realtime systems @@ -630,7 +629,7 @@ Optimizing string handling 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 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. 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 # string already -However it is not efficient to do: +However, it is not efficient to do: .. code-block:: Nim 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 -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:\: .. code-block:: Nim 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! Usage of ``shallow`` is always safe once you know the string won't be modified diff --git a/doc/niminst.rst b/doc/niminst.rst index bf5cb0f50f46f..adb5e6f1fb2c8 100644 --- a/doc/niminst.rst +++ b/doc/niminst.rst @@ -59,7 +59,7 @@ Key description ``Description`` the project's description ``App`` the application's type: "Console" or "GUI". If "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 ==================== ======================================================= @@ -114,7 +114,7 @@ Listed files will be installed into the OS's native library directory 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 (``$appdir``). @@ -149,7 +149,7 @@ Key description ==================== ======================================================= ``InstallScript`` boolean flag whether an installation shell script 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. 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 diff --git a/doc/testament.rst b/doc/testament.rst index 1b2b71c18b58a..e2612711bea1a 100644 --- a/doc/testament.rst +++ b/doc/testament.rst @@ -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, supports multiple targets (C, C++, ObjectiveC, JavaScript, etc), simulated `Dry-Runs `_, -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. @@ -115,9 +115,9 @@ Example "template" **to edit** and write a Testament unittest: * 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(). `_ -* `Nim itself uses Testament, so theres plenty of test examples. `_ +* `Nim itself uses Testament, so there are plenty of test examples. `_ * 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. `_ @@ -172,7 +172,7 @@ JavaScript tests: import jsconsole console.log("My Frontend Project") -Compile time tests: +Compile-time tests: .. code-block:: nim diff --git a/doc/tools.rst b/doc/tools.rst index df4d2e99f503f..f231cdc7d6432 100644 --- a/doc/tools.rst +++ b/doc/tools.rst @@ -14,7 +14,7 @@ The standard distribution ships with the following tools: - | `Nimsuggest for IDE support `_ | 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. - | `C2nim `_ @@ -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, it can generate statistics about test cases, supports multiple targets (C, JS, etc), `simulated Dry-Runs `_, - 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. diff --git a/doc/tut1.rst b/doc/tut1.rst index 68e74df52218e..415a44f5f01bd 100644 --- a/doc/tut1.rst +++ b/doc/tut1.rst @@ -18,7 +18,7 @@ Introduction This document is a tutorial for the programming language *Nim*. 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 `_ 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 Nim's documentation, follow the `Nim style guide `_. @@ -41,9 +41,9 @@ Save this code to the file "greetings.nim". Now compile and run it:: nim compile --run greetings.nim -With the ``--run`` `switch `_ Nim +With the ``--run`` `switch `_ Nim 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 @@ -55,17 +55,17 @@ To compile a release version use:: 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 `turned off and optimizations are turned on -`_. +`_. 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 starts. Indentation is Nim's way of grouping statements. Indentation is 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 returned by the `readLine `_ procedure. Since the compiler knows that `readLine `_ returns a string, @@ -96,16 +96,16 @@ keywords, comments, operators, and other punctuation marks. 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`` means tabulator, etc. There are also *raw* string literals: .. code-block:: 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 multiple lines and the ``\`` is not an escape character either. They are very 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, 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``, binary literals with ``0b`` and octal literals with ``0o``. A leading zero 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 "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 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 -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. @@ -296,10 +296,10 @@ a multi-branch: else: 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. -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.) 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`` 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 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`` -(`backwards index operator `_) to simplify +(`backward index operator `_) to simplify counting to one less than the higher index: .. code-block:: nim @@ -520,7 +520,7 @@ differences: * The compiler checks the semantics and produces code *only* for the statements 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. @@ -530,15 +530,15 @@ Statements and indentation Now that we covered the basic control flow statements, let's return to Nim 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: -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 contain other statements. To avoid ambiguities, complex statements must always be indented, but single simple statements do not: .. code-block:: nim - # no indentation needed for single assignment statement: + # no indentation needed for single-assignment statement: if x: x = false # indentation needed for nested if statement: @@ -554,8 +554,8 @@ be indented, but single simple statements do not: y = false -*Expressions* are parts of a statement which usually result in a value. The -condition in an if statement is an example for an expression. Expressions can +*Expressions* are parts of a statement that usually result in a value. The +condition in an if statement is an example of an expression. Expressions can contain indentation at certain places for better readability: .. code-block:: nim @@ -617,7 +617,7 @@ Some terminology: in the example ``question`` is called a (formal) *parameter*, Result variable --------------- 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 automatically at the end of a procedure if there is no ``return`` statement at the exit. @@ -637,9 +637,9 @@ the exit. 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 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 -initialisation. +initialization. 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, @@ -798,7 +798,7 @@ Apart from a few built-in keyword operators such as ``and``, ``or``, ``not``, 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. The operator's precedence is determined by its first character. The details @@ -824,7 +824,7 @@ Forward declarations Every variable, procedure, etc. needs to be declared before it can be used. (The reason for this is that it is non-trivial to avoid this need in a -language that supports meta programming as extensively as Nim does.) +language that supports metaprogramming as extensively as Nim does.) However, this cannot be done for mutually recursive procedures: .. code-block:: nim @@ -900,13 +900,12 @@ important differences: ``yield`` statement). * Iterators have no implicit ``result`` variable. * Iterators do not support recursion. -* Iterators cannot be forward declared, because the compiler must be able - to inline an iterator. (This restriction will be gone in a +* Iterators cannot be forward declared, because the compiler must be able to inline an iterator. (This restriction will be gone in a future version of the compiler.) However, you can also use a ``closure`` iterator to get a different set of -restrictions. See `first class iterators `_ -for details. Iterators can have the same name and parameters as a proc, since +restrictions. See `first-class iterators `_ +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 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 @@ -940,10 +939,10 @@ evaluation. For example: Characters ---------- 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. 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. 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. 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 shifting with the ``shr`` operator. Bit shifting operators always treat their arguments as *unsigned*. For `arithmetic bit shifts`:idx: ordinary @@ -1012,7 +1011,7 @@ cannot be detected at compile time). 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, ``float`` is always 64-bits. @@ -1030,9 +1029,8 @@ type: The common operators ``+ - * / < <= == != > >=`` are defined for floats and follow the IEEE-754 standard. -Automatic type conversion in expressions with different kinds of floating -point types is performed: the smaller type is converted to the larger. Integer -types are **not** converted to floating point types automatically, nor vice +Automatic type conversion in expressions with different kinds of floating-point types is performed: the smaller type is converted to the larger. Integer +types are **not** converted to floating-point types automatically, nor vice versa. Use the `toInt `_ and `toFloat `_ 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. These values are a set of ordered symbols. Each symbol is mapped 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 :test: "nim c $1" @@ -1135,6 +1133,7 @@ Enumerations, integer types, ``char`` and ``bool`` (and subranges) are called ordinal types. Ordinal types have quite a few special operations: + ----------------- -------------------------------------------------------- Operation Comment ----------------- -------------------------------------------------------- @@ -1150,6 +1149,7 @@ Operation Comment ``pred(x, n)`` returns the `n`'th predecessor of `x` ----------------- -------------------------------------------------------- + The `inc `_, `dec `_, `succ `_ and `pred `_ operations can fail by raising an `EOutOfRange` or `EOverflow` exception. (If the code has been @@ -1187,7 +1187,7 @@ Sets 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. 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 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 -subdivided in height levels accessed through their integer index: +subdivided into height levels accessed through their integer index: .. code-block:: nim 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 provided by the sequence. The ``for`` statement is looping over the results from the `items() `_ iterator from the `system -`_ module. But if you use the two variable form, the first +`_ module. But if you use the two-variable form, the first 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 `pairs() `_ iterator from the `system @@ -1339,7 +1339,7 @@ Open arrays ----------- **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 this. Openarrays are always indexed with an ``int`` starting at position 0. The `len `_, `low `_ @@ -1591,10 +1591,10 @@ having the same field types. 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 variables. An example of this is the `splitFile `_ -proc from the `os module `_ which returns the directory, name and +proc from the `os module `_ which returns the directory, name, and 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, -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: .. 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. Untraced references are also called *pointers*. Traced references point to -objects in a garbage collected heap, untraced references point to -manually allocated objects or to objects elsewhere in memory. Thus -untraced references are *unsafe*. However for certain low-level operations +objects in a garbage-collected heap, untraced references point to +manually allocated objects or objects elsewhere in memory. Thus +untraced references are *unsafe*. However, for certain low-level operations (e.g., accessing the hardware), untraced references are necessary. Traced references are declared with the **ref** keyword; untraced references 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 tuple/object field operator) and ``[]`` (array/string/sequence index operator) operators perform implicit dereferencing operations for reference types: @@ -1688,9 +1688,9 @@ listed in the `manual `_. 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". -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 type to the other. Examples are provided in the `manual `_. @@ -1775,7 +1775,7 @@ Excluding 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. .. 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 symbols, thereby making symbols available, but needing to be qualified -to be used. +in order to be used. .. code-block:: nim from mymodule import x, y, z diff --git a/doc/tut3.rst b/doc/tut3.rst index a39074db99080..a159f0d829a8f 100644 --- a/doc/tut3.rst +++ b/doc/tut3.rst @@ -14,7 +14,7 @@ Introduction "With Great Power Comes Great Responsibility." -- Spider Man's Uncle 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. 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 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 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``! @@ -52,10 +52,10 @@ Untyped Arguments Untyped macro arguments are passed to the macro before they are 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 -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 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. 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 identifier nodes are resolved as symbols, implicit type 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. But all other types, such as ``int``, ``float`` or ``MyObjectType`` 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 -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``: .. 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 `_ module. But a more interactive way to explore the Nim 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 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: .. code-block:: nim @@ -176,7 +176,7 @@ Generating Code 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 ``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 tree with calls to ``newTree`` and ``newLit`` the macro ``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 implement the ``myDebug`` macro mentioned earlier. The first thing to 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 -correct argument should be look like. +print the argument. This way it is possible to get an idea of what a +correct argument should look like. .. code-block:: nim :test: "nim c $1" @@ -250,9 +250,9 @@ correct argument should be look like. 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 -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. .. code-block:: nim @@ -292,13 +292,13 @@ used to get this output. 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 expressions, making the code incomprehensible for anybody who does 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 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 self-explanatory code: when it comes to macros, the implementation is not enough for documentation. @@ -309,7 +309,7 @@ Limitations 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 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. @@ -348,7 +348,7 @@ OpenGL Sandbox -------------- 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. `OpenGL Sandbox `_