Markdown links migration part 1 (#20319)

Markdown link migration part 1

Also the warning is improved a bit.

Local links (targeting inside its document) which had had a full anchor
were turned into concise form.
The very fact that they existed may be due to the bug in
reference to subsections fixed https://github.com/nim-lang/Nim/pull/20279,
now they are working well (both in RST syntax and
new Pandoc Markdown syntax implemented in
https://github.com/nim-lang/Nim/pull/20304)
This commit is contained in:
Andrey Makarov 2022-09-09 17:45:54 +03:00 • committed by GitHub
commit f6ee066ee2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 256 additions and 240 deletions

View file

@ -17,7 +17,7 @@
Introduction Introduction
============ ============
The `Nim Compiler User Guide <nimc.html>`_ documents the typical The [Nim Compiler User Guide](nimc.html) documents the typical
compiler invocation, using the `compile`:option: compiler invocation, using the `compile`:option:
or `c`:option: command to transform a or `c`:option: command to transform a
``.nim`` file into one or more ``.c`` files which are then compiled with the ``.nim`` file into one or more ``.c`` files which are then compiled with the
@ -26,12 +26,12 @@ to compile to C++, Objective-C, or JavaScript. This document tries to
concentrate in a single place all the backend and interfacing options. concentrate in a single place all the backend and interfacing options.
The Nim compiler supports mainly two backend families: the C, C++ and The Nim compiler supports mainly two backend families: the C, C++ and
Objective-C targets and the JavaScript target. `The C like targets Objective-C targets and the JavaScript target. [The C like targets](
<#backends-the-c-like-targets>`_ creates source files that can be compiled #backends-the-c-like-targets) creates source files that can be compiled
into a library or a final executable. `The JavaScript target into a library or a final executable. [The JavaScript target](
<#backends-the-javascript-target>`_ can generate a ``.js`` file which you #backends-the-javascript-target) can generate a ``.js`` file which you
reference from an HTML file or create a `standalone Node.js program reference from an HTML file or create a [standalone Node.js program](
<http://nodejs.org>`_. http://nodejs.org).
On top of generating libraries or standalone applications, Nim offers On top of generating libraries or standalone applications, Nim offers
bidirectional interfacing with the backend targets through generic and bidirectional interfacing with the backend targets through generic and
@ -64,8 +64,8 @@ line invocations:
``` ```
The compiler commands select the target backend, but if needed you can The compiler commands select the target backend, but if needed you can
`specify additional switches for cross-compilation [specify additional switches for cross-compilation](
<nimc.html#crossminuscompilation>`_ to select the target CPU, operative system nimc.html#crossminuscompilation) to select the target CPU, operative system
or compiler/linker commands. or compiler/linker commands.
@ -89,15 +89,15 @@ available. This includes:
* some modules of the standard library * some modules of the standard library
* proper 64-bit integer arithmetic * proper 64-bit integer arithmetic
To compensate, the standard library has modules `catered to the JS backend To compensate, the standard library has modules [catered to the JS backend](
<lib.html#pure-libraries-modules-for-js-backend>`_ lib.html#pure-libraries-modules-for-js-backend)
and more support will come in the future (for instance, Node.js bindings and more support will come in the future (for instance, Node.js bindings
to get OS info). to get OS info).
To compile a Nim module into a ``.js`` file use the `js`:option: command; the To compile a Nim module into a ``.js`` file use the `js`:option: command; the
default is a ``.js`` file that is supposed to be referenced in an ``.html`` default is a ``.js`` file that is supposed to be referenced in an ``.html``
file. However, you can also run the code with `nodejs`:idx: file. However, you can also run the code with `nodejs`:idx:
(`<http://nodejs.org>`_): (http://nodejs.org):
```cmd ```cmd
nim js -d:nodejs -r examples/hallo.nim nim js -d:nodejs -r examples/hallo.nim
@ -120,14 +120,14 @@ component?).
Nim code calling the backend Nim code calling the backend
---------------------------- ----------------------------
Nim code can interface with the backend through the `Foreign function Nim code can interface with the backend through the [Foreign function
interface <manual.html#foreign-function-interface>`_ mainly through the interface](manual.html#foreign-function-interface) mainly through the
`importc pragma <manual.html#foreign-function-interface-importc-pragma>`_. [importc pragma](manual.html#foreign-function-interface-importc-pragma).
The `importc` pragma is the *generic* way of making backend symbols available The `importc` pragma is the *generic* way of making backend symbols available
in Nim and is available in all the target backends (JavaScript too). The C++ in Nim and is available in all the target backends (JavaScript too). The C++
or Objective-C backends have their respective `ImportCpp or Objective-C backends have their respective [ImportCpp](
<manual.html#implementation-specific-pragmas-importcpp-pragma>`_ and manual.html#implementation-specific-pragmas-importcpp-pragma) and
`ImportObjC <manual.html#implementation-specific-pragmas-importobjc-pragma>`_ [ImportObjC](manual.html#implementation-specific-pragmas-importobjc-pragma)
pragmas to call methods from classes. pragmas to call methods from classes.
Whenever you use any of these pragmas you need to integrate native code into Whenever you use any of these pragmas you need to integrate native code into
@ -139,19 +139,20 @@ However, for the C like targets you need to link external code either
statically or dynamically. The preferred way of integrating native code is to statically or dynamically. The preferred way of integrating native code is to
use dynamic linking because it allows you to compile Nim programs without use dynamic linking because it allows you to compile Nim programs without
the need for having the related development libraries installed. This is done the need for having the related development libraries installed. This is done
through the `dynlib pragma for import through the [dynlib pragma for import](
<manual.html#foreign-function-interface-dynlib-pragma-for-import>`_, though manual.html#foreign-function-interface-dynlib-pragma-for-import), though
more specific control can be gained using the `dynlib module <dynlib.html>`_. more specific control can be gained using the [dynlib module](dynlib.html).
The `dynlibOverride <nimc.html#dynliboverride>`_ command line switch allows The [dynlibOverride](nimc.html#dynliboverride) command line switch allows
to avoid dynamic linking if you need to statically link something instead. to avoid dynamic linking if you need to statically link something instead.
Nim wrappers designed to statically link source files can use the `compile Nim wrappers designed to statically link source files can use the [compile
pragma <manual.html#implementation-specific-pragmas-compile-pragma>`_ if pragma](manual.html#implementation-specific-pragmas-compile-pragma) if
there are few sources or providing them along the Nim code is easier than using there are few sources or providing them along the Nim code is easier than using
a system library. Libraries installed on the host system can be linked in with a system library. Libraries installed on the host system can be linked in with
the `PassL pragma <manual.html#implementation-specific-pragmas-passl-pragma>`_. the [PassL pragma](manual.html#implementation-specific-pragmas-passl-pragma).
To wrap native code, take a look at the `c2nim tool <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ which helps To wrap native code, take a look at the [c2nim tool](
https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst) which helps
with the process of scanning and transforming header files into a Nim with the process of scanning and transforming header files into a Nim
interface. interface.
@ -223,16 +224,16 @@ from the previous section):
Compile the Nim code to JavaScript with `nim js -o:calculator.js Compile the Nim code to JavaScript with `nim js -o:calculator.js
calculator.nim`:cmd: and open ``host.html`` in a browser. If the browser supports calculator.nim`:cmd: and open ``host.html`` in a browser. If the browser supports
javascript, you should see the value `10` in the browser's console. Use the javascript, you should see the value `10` in the browser's console. Use the
`dom module <dom.html>`_ for specific DOM querying and modification procs [dom module](dom.html) for specific DOM querying and modification procs
or take a look at `karax <https://github.com/pragmagic/karax>`_ for how to or take a look at [karax](https://github.com/pragmagic/karax) for how to
develop browser-based applications. develop browser-based applications.
Backend code calling Nim Backend code calling Nim
------------------------ ------------------------
Backend code can interface with Nim code exposed through the `exportc Backend code can interface with Nim code exposed through the [exportc
pragma <manual.html#foreign-function-interface-exportc-pragma>`_. The pragma](manual.html#foreign-function-interface-exportc-pragma). The
`exportc` pragma is the *generic* way of making Nim symbols available to `exportc` pragma is the *generic* way of making Nim symbols available to
the backends. By default, the Nim compiler will mangle all the Nim symbols to the backends. By default, the Nim compiler will mangle all the Nim symbols to
avoid any name collision, so the most significant thing the `exportc` pragma avoid any name collision, so the most significant thing the `exportc` pragma
@ -347,8 +348,8 @@ Nimcache naming logic
The `nimcache`:idx: directory is generated during compilation and will hold The `nimcache`:idx: directory is generated during compilation and will hold
either temporary or final files depending on your backend target. The default either temporary or final files depending on your backend target. The default
name for the directory depends on the used backend and on your OS but you can name for the directory depends on the used backend and on your OS but you can
use the `--nimcache`:option: `compiler switch use the `--nimcache`:option: [compiler switch](
<nimc.html#compiler-usage-commandminusline-switches>`_ to change it. nimc.html#compiler-usage-commandminusline-switches) to change it.
Memory management Memory management
@ -366,15 +367,15 @@ aware of who controls what to avoid crashing.
Strings and C strings Strings and C strings
--------------------- ---------------------
The manual mentions that `Nim strings are implicitly convertible to The manual mentions that [Nim strings are implicitly convertible to
cstrings <manual.html#types-cstring-type>`_ which makes interaction usually cstrings](manual.html#types-cstring-type) which makes interaction usually
painless. Most C functions accepting a Nim string converted to a 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 `cstring` will likely not need to keep this string around and by the time
they return the string won't be needed anymore. 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 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 as a `cstring`, you will need to manually prevent the string data
from being freed with `GC_ref <system.html#GC_ref,string>`_ and `GC_unref from being freed with [GC_ref](system.html#GC_ref,string) and [GC_unref](
<system.html#GC_unref,string>`_. system.html#GC_unref,string).
A similar thing happens with C code invoking Nim code which returns a A similar thing happens with C code invoking Nim code which returns a
`cstring`. Consider the following proc: `cstring`. Consider the following proc:
@ -393,10 +394,10 @@ Custom data types
Just like strings, custom data types that are to be shared between Nim and Just like strings, custom data types that are to be shared between Nim and
the backend will need careful consideration of who controls who. If you want the backend will need careful consideration of who controls who. If you want
to hand a Nim reference to C code, you will need to use `GC_ref to hand a Nim reference to C code, you will need to use [GC_ref](
<system.html#GC_ref,ref.T>`_ to mark the reference as used, so it does not get system.html#GC_ref,ref.T) 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 freed. And for the C backend you will need to expose the [GC_unref](
<system.html#GC_unref,ref.T>`_ proc to clean up this memory when it is not system.html#GC_unref,ref.T) proc to clean up this memory when it is not
required anymore. required anymore.
Again, if you are wrapping a library which *mallocs* and *frees* data Again, if you are wrapping a library which *mallocs* and *frees* data

View file

@ -216,7 +216,7 @@ must be marked as deprecated using the `deprecated` pragma:
``` ```
See also `Deprecated <manual.html#pragmas-deprecated-pragma>`_ See also [Deprecated](manual.html#pragmas-deprecated-pragma)
pragma in the manual. pragma in the manual.
@ -242,7 +242,7 @@ as well as `testament`:cmd: and guarantee they stay in sync.
result = a & "Bar" result = a & "Bar"
``` ```
See `parentDir <os.html#parentDir,string>`_ example. See [parentDir](os.html#parentDir,string) example.
The RestructuredText Nim uses has a special syntax for including code snippets The RestructuredText Nim uses has a special syntax for including code snippets
embedded in documentation; these are not run by `nim doc`:cmd: and therefore are embedded in documentation; these are not run by `nim doc`:cmd: and therefore are
@ -297,7 +297,7 @@ the first is preferred.
When you specify an *RST role* (highlighting/interpretation marker) do it When you specify an *RST role* (highlighting/interpretation marker) do it
in the postfix form for uniformity, that is after \`text in backticks\`. in the postfix form for uniformity, that is after \`text in backticks\`.
For example an ``:idx:`` role for referencing a topic ("SQLite" in the For example an ``:idx:`` role for referencing a topic ("SQLite" in the
example below) from `Nim Index`_ can be used in doc comment this way: example below) from [Nim Index] can be used in doc comment this way:
```nim ```nim
## A higher level `SQLite`:idx: database wrapper. ## A higher level `SQLite`:idx: database wrapper.
@ -466,8 +466,8 @@ General commit rules
2. If you introduce changes which affect backward compatibility, 2. If you introduce changes which affect backward compatibility,
make breaking changes, or have PR which is tagged as ``[feature]``, make breaking changes, or have PR which is tagged as ``[feature]``,
the changes should be mentioned in `the changelog the changes should be mentioned in [the changelog](
<https://github.com/nim-lang/Nim/blob/devel/changelog.md>`_. https://github.com/nim-lang/Nim/blob/devel/changelog.md).
3. All changes introduced by the commit (diff lines) must be related to the 3. All changes introduced by the commit (diff lines) must be related to the
subject of the commit. subject of the commit.
@ -525,8 +525,10 @@ Continuous Integration (CI)
documentation only changes), add ``[skip ci]`` to your commit message title. documentation only changes), add ``[skip ci]`` to your commit message title.
This convention is supported by our GitHub actions pipelines and our azure pipeline This convention is supported by our GitHub actions pipelines and our azure pipeline
(using custom logic, which should complete in < 1mn) as well as our former other pipelines: (using custom logic, which should complete in < 1mn) as well as our former other pipelines:
`Appveyor <https://www.appveyor.com/docs/how-to/filtering-commits/#skip-directive-in-commit-message>`_ [Appveyor](
and `Travis <https://docs.travis-ci.com/user/customizing-the-build/#skipping-a-build>`_. https://www.appveyor.com/docs/how-to/filtering-commits/#skip-directive-in-commit-message)
and [Travis](
https://docs.travis-ci.com/user/customizing-the-build/#skipping-a-build).
2. Consider enabling CI (azure, GitHub actions and builds.sr.ht) in your own Nim fork, and 2. Consider enabling CI (azure, GitHub actions and builds.sr.ht) in your own Nim fork, and
waiting for CI to be green in that fork (fixing bugs as needed) before waiting for CI to be green in that fork (fixing bugs as needed) before
@ -568,7 +570,8 @@ Code reviews
2. When reviewing large diffs that may involve code moving around, GitHub's interface 2. When reviewing large diffs that may involve code moving around, GitHub's interface
doesn't help much, as it doesn't highlight moves. Instead, you can use something doesn't help much, as it doesn't highlight moves. Instead, you can use something
like this, see visual results `here <https://github.com/nim-lang/Nim/pull/10431#issuecomment-456968196>`_: like this, see visual results [here](
https://github.com/nim-lang/Nim/pull/10431#issuecomment-456968196):
```cmd ```cmd
git fetch origin pull/10431/head && git checkout FETCH_HEAD git fetch origin pull/10431/head && git checkout FETCH_HEAD

View file

@ -98,7 +98,8 @@ Lifetime-tracking hooks
The memory management for Nim's standard `string` and `seq` types as The memory management for Nim's standard `string` and `seq` types as
well as other standard collections is performed via so-called well as other standard collections is performed via so-called
"Lifetime-tracking hooks", which are particular `type bound operators <manual.html#procedures-type-bound-operators>`_. "Lifetime-tracking hooks", which are particular [type bound operators](
manual.html#procedures-type-bound-operators).
There are 4 different hooks for each (generic or concrete) object type `T` (`T` can also be a There are 4 different hooks for each (generic or concrete) object type `T` (`T` can also be a
`distinct` type) that are called implicitly by the compiler. `distinct` type) that are called implicitly by the compiler.

View file

@ -14,7 +14,7 @@ Introduction
============ ============
This document describes the `documentation generation tools`:idx: built into This document describes the `documentation generation tools`:idx: built into
the `Nim compiler <nimc.html>`_, which can generate HTML, Latex and JSON output the [Nim compiler](nimc.html), which can generate HTML, Latex and JSON output
from input ``.nim`` files and projects, as well as HTML and LaTeX from input RST from input ``.nim`` files and projects, as well as HTML and LaTeX from input RST
(reStructuredText) files. The output documentation will include the module (reStructuredText) files. The output documentation will include the module
dependencies (`import`), any top-level documentation comments (`##`), and dependencies (`import`), any top-level documentation comments (`##`), and
@ -59,8 +59,8 @@ Documentation Comments
---------------------- ----------------------
Any comments which are preceded by a double-hash (`##`), are interpreted as Any comments which are preceded by a double-hash (`##`), are interpreted as
documentation. Comments are parsed as RST (see `reference documentation. Comments are parsed as RST (see [reference](
<http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_), providing http://docutils.sourceforge.net/docs/user/rst/quickref.html)), providing
Nim module authors the ability to easily generate richly formatted Nim module authors the ability to easily generate richly formatted
documentation with only their well-documented code! documentation with only their well-documented code!
Basic Markdown syntax is also supported inside the doc comments. Basic Markdown syntax is also supported inside the doc comments.
@ -148,7 +148,7 @@ Partial Output::
proc helloWorld(times: int) {.raises: [], tags: [].} proc helloWorld(times: int) {.raises: [], tags: [].}
... ...
The full output can be seen here: `docgen_sample.html <docgen_sample.html>`_. The full output can be seen here: [docgen_sample.html](docgen_sample.html).
It runs after semantic checking and includes pragmas attached implicitly by the It runs after semantic checking and includes pragmas attached implicitly by the
compiler. compiler.
@ -247,7 +247,7 @@ Link text is either one word or a group of words enclosed by backticks `\``
Link text will be displayed *as is* while *link target* will be set to Link text will be displayed *as is* while *link target* will be set to
the anchor \[*] of Nim symbol that corresponds to link text. the anchor \[*] of Nim symbol that corresponds to link text.
[*] anchors' format is described in `HTML anchor generation`_ section below. \[*] anchors' format is described in [HTML anchor generation] section below.
If you have a constant: If you have a constant:
@ -435,11 +435,11 @@ This will generate an index of all the exported symbols in the input Nim
module, and put it into a neighboring file with the extension of ``.idx``. The module, and put it into a neighboring file with the extension of ``.idx``. The
index file is line-oriented (newlines have to be escaped). Each line index file is line-oriented (newlines have to be escaped). Each line
represents a tab-separated record of several columns, the first two mandatory, represents a tab-separated record of several columns, the first two mandatory,
the rest optional. See the `Index (idx) file format`_ section for details. the rest optional. See the [Index (idx) file format] section for details.
Once index files have been generated for one or more modules, the Nim Once index files have been generated for one or more modules, the Nim
compiler command `buildIndex directory` can be run to go over all the index compiler command `buildIndex directory` can be run to go over all the index
files in the specified directory to generate a `theindex.html <theindex.html>`_ files in the specified directory to generate a [theindex.html](theindex.html)
file. file.
See source switch See source switch
@ -488,7 +488,7 @@ the `rst2html`:option: and `rst2tex`:option: commands. Documents like this one a
initially written in a dialect of RST which adds support for Nim source code initially written in a dialect of RST which adds support for Nim source code
highlighting with the ``.. code-block:: nim`` prefix. ``code-block`` also highlighting with the ``.. code-block:: nim`` prefix. ``code-block`` also
supports highlighting of a few other languages supported by the supports highlighting of a few other languages supported by the
`packages/docutils/highlite module <highlite.html>`_. [packages/docutils/highlite module](highlite.html).
Usage: Usage:
@ -550,38 +550,38 @@ Callable type Suffix
The relationship of type to suffix is made by the proc `complexName` in the The relationship of type to suffix is made by the proc `complexName` in the
``compiler/docgen.nim`` file. Here are some examples of complex names for ``compiler/docgen.nim`` file. Here are some examples of complex names for
symbols in the `system module <system.html>`_. symbols in the [system module](system.html).
* `type SomeSignedInt = int | int8 | int16 | int32 | int64` **=>** * `type SomeSignedInt = int | int8 | int16 | int32 | int64` **=>**
`#SomeSignedInt <system.html#SomeSignedInt>`_ [#SomeSignedInt](system.html#SomeSignedInt)
* `var globalRaiseHook: proc (e: ref E_Base): bool {.nimcall.}` **=>** * `var globalRaiseHook: proc (e: ref E_Base): bool {.nimcall.}` **=>**
`#globalRaiseHook <system.html#globalRaiseHook>`_ [#globalRaiseHook](system.html#globalRaiseHook)
* `const NimVersion = "0.0.0"` **=>** * `const NimVersion = "0.0.0"` **=>**
`#NimVersion <system.html#NimVersion>`_ [#NimVersion](system.html#NimVersion)
* `proc getTotalMem(): int {.rtl, raises: [], tags: [].}` **=>** * `proc getTotalMem(): int {.rtl, raises: [], tags: [].}` **=>**
`#getTotalMem, <system.html#getTotalMem>`_ [#getTotalMem](system.html#getTotalMem)
* `proc len[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}` **=>** * `proc len[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}` **=>**
`#len,seq[T] <system.html#len,seq[T]>`_ [#len,seq[T]](system.html#len,seq[T])
* `iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}` **=>** * `iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}` **=>**
`#pairs.i,seq[T] <iterators.html#pairs.i,seq[T]>`_ [#pairs.i,seq[T]](iterators.html#pairs.i,seq[T])
* `template newException[](exceptn: typedesc; message: string; * `template newException[](exceptn: typedesc; message: string;
parentException: ref Exception = nil): untyped` **=>** parentException: ref Exception = nil): untyped` **=>**
`#newException.t,typedesc,string,ref.Exception [#newException.t,typedesc,string,ref.Exception](
<system.html#newException.t,typedesc,string,ref.Exception>`_ system.html#newException.t,typedesc,string,ref.Exception)
Index (idx) file format Index (idx) file format
======================= =======================
Files with the ``.idx`` extension are generated when you use the `Index Files with the ``.idx`` extension are generated when you use the [Index
switch <#related-options-index-switch>`_ along with commands to generate switch] along with commands to generate
documentation from source or text files. You can programmatically generate documentation from source or text files. You can programmatically generate
indices with the `setIndexTerm() indices with the [setIndexTerm()](
<rstgen.html#setIndexTerm,RstGenerator,string,string,string,string,string>`_ rstgen.html#setIndexTerm,RstGenerator,string,string,string,string,string)
and `writeIndexFile() <rstgen.html#writeIndexFile,RstGenerator,string>`_ procs. and `writeIndexFile() <rstgen.html#writeIndexFile,RstGenerator,string>`_ procs.
The purpose of `idx` files is to hold the interesting symbols and their HTML The purpose of `idx` files is to hold the interesting symbols and their HTML
references so they can be later concatenated into a big index file with references so they can be later concatenated into a big index file with
`mergeIndexes() <rstgen.html#mergeIndexes,string>`_. This section documents [mergeIndexes()](rstgen.html#mergeIndexes,string). This section documents
the file format in detail. the file format in detail.
Index files are line-oriented and tab-separated (newline and tab characters Index files are line-oriented and tab-separated (newline and tab characters
@ -626,16 +626,16 @@ final index, and TOC entries found in ``.nim`` files are discarded.
Additional resources Additional resources
==================== ====================
* `Nim Compiler User Guide <nimc.html#compiler-usage-commandminusline-switches>`_ * [Nim Compiler User Guide](nimc.html#compiler-usage-commandminusline-switches)
* Documentation for `rst module <rst.html>`_ -- Nim RST/Markdown parser. * Documentation for [rst module](rst.html) -- Nim RST/Markdown parser.
* `RST Quick Reference * [RST Quick Reference](
<http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_ http://docutils.sourceforge.net/docs/user/rst/quickref.html)
The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and
``config/nimdoc.tex.cfg`` configuration files. You can add and modify these ``config/nimdoc.tex.cfg`` configuration files. You can add and modify these
files to your project to change the look of the docgen output. files to your project to change the look of the docgen output.
You can import the `packages/docutils/rstgen module <rstgen.html>`_ in your You can import the [packages/docutils/rstgen module](rstgen.html) in your
programs if you want to reuse the compiler's documentation generation procs. programs if you want to reuse the compiler's documentation generation procs.

View file

@ -22,16 +22,16 @@ About this document
precise wording. This manual is constantly evolving into a proper specification. precise wording. This manual is constantly evolving into a proper specification.
**Note**: The experimental features of Nim are **Note**: The experimental features of Nim are
covered `here <manual_experimental.html>`_. covered [here](manual_experimental.html).
**Note**: Assignments, moves, and destruction are specified in **Note**: Assignments, moves, and destruction are specified in
the `destructors <destructors.html>`_ document. the [destructors](destructors.html) document.
This document describes the lexis, the syntax, and the semantics of the Nim language. This document describes the lexis, the syntax, and the semantics of the Nim language.
To learn how to compile Nim programs and generate documentation see To learn how to compile Nim programs and generate documentation see
the `Compiler User Guide <nimc.html>`_ and the `DocGen Tools Guide <docgen.html>`_. the [Compiler User Guide](nimc.html) and the [DocGen Tools Guide](docgen.html).
The language constructs are explained using an extended BNF, in which `(a)*` The language constructs are explained using an extended BNF, in which `(a)*`
means 0 or more `a`'s, `a+` means 1 or more `a`'s, and `(a)?` means an means 0 or more `a`'s, `a+` means 1 or more `a`'s, and `(a)?` means an
@ -94,8 +94,8 @@ In a typical Nim program, most of the code is compiled into the executable.
However, some code may be executed at However, some 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 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 on Compile-Time Execution] for
details. We use the term `runtime`:idx: to cover both compile-time execution details. We use the term `runtime`:idx: to cover both compile-time execution
and code execution in the executable. and code execution in the executable.
@ -111,7 +111,7 @@ A `panic`:idx: is an error that the implementation detects
and reports at runtime. The method for reporting such errors is via and reports at runtime. The method for reporting such errors is via
*raising exceptions* or *dying with a fatal error*. However, the implementation *raising exceptions* or *dying with a fatal error*. However, the implementation
provides a means to disable these `runtime checks`:idx:. See the section provides a means to disable these `runtime checks`:idx:. See the section
pragmas_ for details. [Pragmas] for details.
Whether a panic results in an exception or in a fatal error is Whether a panic results in an exception or in a fatal error is
implementation specific. Thus, the following program is invalid; even though the implementation specific. Thus, the following program is invalid; even though the
@ -499,7 +499,7 @@ Rationale: It enables the efficient support of `array[char, int]` or
`set[char]`. `set[char]`.
The `Rune` type can represent any Unicode character. The `Rune` type can represent any Unicode character.
`Rune` is declared in the `unicode module <unicode.html>`_. `Rune` is declared in the [unicode module](unicode.html).
A character literal that does not end in `'` is interpreted as `'` if there A character literal that does not end in `'` is interpreted as `'` if there
is a preceding backtick token. There must be no whitespace between the preceding is a preceding backtick token. There must be no whitespace between the preceding
@ -507,7 +507,7 @@ backtick token and the character literal. This special case ensures that a decla
like ``proc `'customLiteral`(s: string)`` is valid. ``proc `'customLiteral`(s: string)`` like ``proc `'customLiteral`(s: string)`` is valid. ``proc `'customLiteral`(s: string)``
is the same as ``proc `'\''customLiteral`(s: string)``. is the same as ``proc `'\''customLiteral`(s: string)``.
See also `custom numeric literals <#custom-numeric-literals>`_. See also [custom numeric literals].
Numeric literals Numeric literals
@ -713,7 +713,7 @@ Syntax
====== ======
This section lists Nim's standard syntax. How the parser handles This section lists Nim's standard syntax. How the parser handles
the indentation is already described in the `Lexical Analysis`_ section. the indentation is already described in the [Lexical Analysis] section.
Nim allows user-definable operators. Nim allows user-definable operators.
Binary operators have 11 different levels of precedence. Binary operators have 11 different levels of precedence.
@ -1100,8 +1100,7 @@ if the literal's value fits this smaller type and such a conversion is less
expensive than other implicit conversions, so `myInt16 + 34` produces expensive than other implicit conversions, so `myInt16 + 34` produces
an `int16` result. an `int16` result.
For further details, see `Convertible relation For further details, see [Convertible relation].
<#type-relations-convertible-relation>`_.
Subrange types Subrange types
@ -1148,8 +1147,7 @@ The following floating-point types are pre-defined:
Automatic type conversion in expressions with different kinds of floating-point Automatic type conversion in expressions with different kinds of floating-point
types is performed: See `Convertible relation types is performed: See [Convertible relation] for further details. Arithmetic
<#type-relations-convertible-relation>`_ for further details. Arithmetic
performed on floating-point types follows the IEEE standard. Integer types are performed on floating-point types follows the IEEE standard. Integer types are
not converted to floating-point types automatically and vice versa. not converted to floating-point types automatically and vice versa.
@ -1229,7 +1227,7 @@ The character type is named `char` in Nim. Its size is one byte.
Thus, it cannot represent a UTF-8 character, but a part of it. Thus, it cannot represent a UTF-8 character, but a part of it.
The `Rune` type is used for Unicode characters, it can represent any Unicode The `Rune` type is used for Unicode characters, it can represent any Unicode
character. `Rune` is declared in the `unicode module <unicode.html>`_. character. `Rune` is declared in the [unicode module](unicode.html).
@ -1315,7 +1313,7 @@ as `MyEnum.value`:
echo MyEnum.amb # OK. echo MyEnum.amb # OK.
``` ```
To implement bit fields with enums see `Bit fields <#set-type-bit-fields>`_ To implement bit fields with enums see [Bit fields].
String type String type
@ -1375,8 +1373,8 @@ arrays, they can be used in case statements:
Per convention, all strings are UTF-8 strings, but this is not enforced. For Per convention, all strings are UTF-8 strings, but this is not enforced. For
example, when reading strings from binary files, they are merely a sequence of example, when reading strings from binary files, they are merely a sequence of
bytes. The index operation `s[i]` means the i-th *char* of `s`, not the bytes. The index operation `s[i]` means the i-th *char* of `s`, not the
i-th *unichar*. The iterator `runes` from the `unicode module i-th *unichar*. The iterator `runes` from the [unicode module](unicode.html)
<unicode.html>`_ can be used for iteration over all Unicode characters. can be used for iteration over all Unicode characters.
cstring type cstring type
@ -1733,8 +1731,8 @@ introduce new object roots apart from `system.RootObj`.
``` ```
The assignment operator for tuples and objects copies each component. The assignment operator for tuples and objects copies each component.
The methods to override this copying behavior are described `here The methods to override this copying behavior are described [here][type
<manual.html#procedures-type-bound-operations>`_. bound operators].
Object construction Object construction
@ -1947,8 +1945,8 @@ dereferencing operations for reference types:
``` ```
Automatic dereferencing can be performed for the first argument of a routine Automatic dereferencing can be performed for the first argument of a routine
call, but this is an experimental feature and is described `here call, but this is an experimental feature and is described [here](
<manual_experimental.html#automatic-dereferencing>`_. manual_experimental.html#automatic-dereferencing).
In order to simplify structural type checking, recursive tuples are not valid: In order to simplify structural type checking, recursive tuples are not valid:
@ -1973,7 +1971,7 @@ This feature is useful if an object should only gain reference semantics:
To allocate a new traced object, the built-in procedure `new` has to be used. To allocate a new traced object, the built-in procedure `new` has to be used.
To deal with untraced memory, the procedures `alloc`, `dealloc` and To deal with untraced memory, the procedures `alloc`, `dealloc` and
`realloc` can be used. The documentation of the `system <system.html>`_ module `realloc` can be used. The documentation of the [system](system.html) module
contains further information. contains further information.
@ -2225,7 +2223,7 @@ the proc that deals with the distinct type's base type, so no code is
generated. generated.
But it seems all this boilerplate code needs to be repeated for the `Euro` But it seems all this boilerplate code needs to be repeated for the `Euro`
currency. This can be solved with templates_. currency. This can be solved with [templates].
```nim test = "nim c $1" ```nim test = "nim c $1"
template additive(typ: typedesc) = template additive(typ: typedesc) =
@ -2341,8 +2339,8 @@ conversions from `string` to `SQL` are allowed:
Now we have compile-time checking against SQL injection attacks. Since Now we have compile-time checking against SQL injection attacks. Since
`"".SQL` is transformed to `SQL("")` no new syntax is needed for nice `"".SQL` is transformed to `SQL("")` no new syntax is needed for nice
looking `SQL` string literals. The hypothetical `SQL` type actually looking `SQL` string literals. The hypothetical `SQL` type actually
exists in the library as the `SqlQuery type <db_common.html#SqlQuery>`_ of exists in the library as the [SqlQuery type](db_common.html#SqlQuery) of
modules like `db_sqlite <db_sqlite.html>`_. modules like [db_sqlite](db_sqlite.html).
Auto type Auto type
@ -2671,7 +2669,7 @@ metatypes `typed` and `typedesc` are not lazy.
Varargs matching Varargs matching
---------------- ----------------
See `Varargs <#types-varargs>`_. See [Varargs].
iterable iterable
@ -2989,8 +2987,7 @@ A const section declares constants whose values are constant expressions:
Once declared, a constant's symbol can be used as a constant expression. Once declared, a constant's symbol can be used as a constant expression.
See `Constants and Constant Expressions <#constants-and-constant-expressions>`_ See [Constants and Constant Expressions] for details.
for details.
Static statement/expression Static statement/expression
--------------------------- ---------------------------
@ -3018,8 +3015,7 @@ Even some code that has side effects is permitted in a static block:
``` ```
There are limitations on what Nim code can be executed at compile time; There are limitations on what Nim code can be executed at compile time;
see `Restrictions on Compile-Time Execution see [Restrictions on Compile-Time Execution] for details.
<#restrictions-on-compileminustime-execution>`_ for details.
It's a static error if the compiler cannot execute the block at compile It's a static error if the compiler cannot execute the block at compile
time. time.
@ -3273,7 +3269,7 @@ The `yield` statement is used instead of the `return` statement in
iterators. It is only valid in iterators. Execution is returned to the body 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 of the for loop that called the iterator. Yield does not end the iteration
process, but the 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`_) starts. See the section about iterators ([Iterators and the for statement])
for further information. for further information.
@ -3786,8 +3782,7 @@ The method call syntax conflicts with explicit generic instantiations:
`p[T](x)` cannot be written as `x.p[T]` because `x.p[T]` is always `p[T](x)` cannot be written as `x.p[T]` because `x.p[T]` is always
parsed as `(x.p)[T]`. parsed as `(x.p)[T]`.
See also: `Limitations of the method call syntax See also: [Limitations of the method call syntax].
<#templates-limitations-of-the-method-call-syntax>`_.
The `[: ]` notation has been designed to mitigate this issue: `x.p[:T]` The `[: ]` notation has been designed to mitigate this issue: `x.p[:T]`
is rewritten by the parser to `p[T](x)`, `x.p[:T](y)` is rewritten to is rewritten by the parser to `p[T](x)`, `x.p[:T](y)` is rewritten to
@ -3873,7 +3868,7 @@ more argument in this case:
``` ```
The command invocation syntax also can't have complex expressions as arguments. The command invocation syntax also can't have complex expressions as arguments.
For example: (`anonymous procs <#procedures-anonymous-procs>`_), `if`, For example: [anonymous procedures], `if`,
`case` or `try`. Function calls with no arguments still need () to `case` or `try`. Function calls with no arguments still need () to
distinguish between a call and the function itself as a first-class value. distinguish between a call and the function itself as a first-class value.
@ -3893,9 +3888,9 @@ or on the stack if the compiler determines that this would be safe.
### Creating closures in loops ### Creating closures in loops
Since closures capture local variables by reference it is often not wanted Since closures capture local variables by reference it is often not wanted
behavior inside loop bodies. See `closureScope behavior inside loop bodies. See [closureScope](
<system.html#closureScope.t,untyped>`_ and `capture system.html#closureScope.t,untyped) and [capture](
<sugar.html#capture.m,varargs[typed],untyped>`_ for details on how to change this behavior. sugar.html#capture.m,varargs[typed],untyped) for details on how to change this behavior.
Anonymous procedures Anonymous procedures
-------------------- --------------------
@ -3912,7 +3907,7 @@ procedures:
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 <sugar.html>`_ module contains the `=>` macro executable code. The [sugar](sugar.html) module contains the `=>` macro
which enables a more succinct syntax for anonymous procedures resembling which enables a more succinct syntax for anonymous procedures resembling
lambdas as they are in languages like JavaScript, C#, etc. lambdas as they are in languages like JavaScript, C#, etc.
@ -3982,7 +3977,7 @@ Type bound operators
A type bound operator is a `proc` or `func` whose name starts with `=` but isn't an operator A type bound operator is a `proc` or `func` whose name starts with `=` but isn't an operator
(i.e. containing only symbols, such as `==`). These are unrelated to setters (i.e. containing only symbols, such as `==`). These are unrelated to setters
(see `properties <manual.html#procedures-properties>`_), which instead end in `=`. (see [Properties]), which instead end in `=`.
A type bound operator declared for a type applies to the type regardless of whether A type bound operator declared for a type applies to the type regardless of whether
the operator is in scope (including if it is private). the operator is in scope (including if it is private).
@ -4024,7 +4019,7 @@ This also means that one cannot override `deepCopy` for both `ptr T` and
used for one pointer type. used for one pointer type.
For more details on some of those procs, see For more details on some of those procs, see
`Lifetime-tracking hooks <destructors.html#lifetimeminustracking-hooks>`_. [Lifetime-tracking hooks](destructors.html#lifetimeminustracking-hooks).
Nonoverloadable builtins Nonoverloadable builtins
------------------------ ------------------------
@ -4037,7 +4032,8 @@ simplicity (they require specialized semantic checking)::
Thus, they act more like keywords than like ordinary identifiers; unlike a Thus, they act more like keywords than like ordinary identifiers; unlike a
keyword however, a redefinition may `shadow`:idx: the definition in keyword however, a redefinition may `shadow`:idx: the definition in
the system_ module. From this list the following should not be written in dot the [system](system.html) 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`:: to `f`::
@ -4589,14 +4585,13 @@ would. For example:
``` ```
See also see `iterable <#overloading-resolution-iterable>`_ for passing iterators to templates and macros. See also [iterable] for passing iterators to templates and macros.
Converters Converters
========== ==========
A converter is like an ordinary proc except that it enhances A converter is like an ordinary proc except that it enhances
the "implicitly convertible" type relation (see `Convertible relation the "implicitly convertible" type relation (see [Convertible relation]):
<#type-relations-convertible-relation>`_):
```nim ```nim
# bad style ahead: Nim is not C. # bad style ahead: Nim is not C.
@ -4859,7 +4854,7 @@ exception.
Exception hierarchy Exception hierarchy
------------------- -------------------
The exception tree is defined in the `system <system.html>`_ module. The exception tree is defined in the [system](system.html) module.
Every exception inherits from `system.Exception`. Exceptions that indicate Every exception inherits from `system.Exception`. Exceptions that indicate
programming bugs inherit from `system.Defect` (which is a subtype of `Exception`) programming bugs inherit from `system.Defect` (which is a subtype of `Exception`)
and are strictly speaking not catchable as they can also be mapped to an operation and are strictly speaking not catchable as they can also be mapped to an operation
@ -5146,8 +5141,8 @@ or global variable and it does not call any routine that has a side effect.
It is a static error to mark a proc/iterator to have no side effect if the compiler cannot verify this. It is a static error to mark a proc/iterator to have no side effect if the compiler cannot verify this.
As a special semantic rule, the built-in `debugEcho As a special semantic rule, the built-in [debugEcho](
<system.html#debugEcho,varargs[typed,]>`_ pretends to be free of side effects system.html#debugEcho,varargs[typed,]) pretends to be free of side effects
so that it can be used for debugging routines marked as `noSideEffect`. so that it can be used for debugging routines marked as `noSideEffect`.
`func` is syntactic sugar for a proc with no side effects: `func` is syntactic sugar for a proc with no side effects:
@ -5202,7 +5197,7 @@ be used:
See also: See also:
- `Shared heap memory management <mm.html>`_. - [Shared heap memory management](mm.html).
@ -6146,8 +6141,8 @@ and are not looked up again. As the example shows, `bindSym` does work with
overloaded symbols implicitly. overloaded symbols implicitly.
Note that the symbol names passed to `bindSym` have to be constant. The Note that the symbol names passed to `bindSym` have to be constant. The
experimental feature `dynamicBindSym` (`experimental manual experimental feature `dynamicBindSym` ([experimental manual](
<manual_experimental.html#dynamic-arguments-for-bindsym>`_) manual_experimental.html#dynamic-arguments-for-bindsym))
allows this value to be computed dynamically. allows this value to be computed dynamically.
Post-statement blocks Post-statement blocks
@ -6287,8 +6282,8 @@ macro to call.
Special Types Special Types
============= =============
static[T] static\[T]
--------- ----------
As their name suggests, static parameters must be constant expressions: As their name suggests, static parameters must be constant expressions:
@ -6341,8 +6336,8 @@ expression by coercing it to a corresponding `static` type:
The compiler will report any failure to evaluate the expression or a The compiler will report any failure to evaluate the expression or a
possible type mismatch error. possible type mismatch error.
typedesc[T] typedesc\[T]
----------- ------------
In many contexts, Nim treats the names of types as regular In many contexts, Nim treats the names of types as regular
values. These values exist only during the compilation phase, but since values. These values exist only during the compilation phase, but since
@ -7051,8 +7046,7 @@ extension the pragma is simply ignored.
immediate pragma immediate pragma
---------------- ----------------
The immediate pragma is obsolete. See `Typed vs untyped parameters The immediate pragma is obsolete. See [Typed vs untyped parameters].
<#templates-typed-vs-untyped-parameters>`_.
redefine pragma redefine pragma
--------------- ---------------
@ -7230,7 +7224,7 @@ 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 too unstable for an otherwise stable release or that the future of the feature
is uncertain (it may be removed at any time). See the is uncertain (it may be removed at any time). See the
`experimental manual <manual_experimental.html>`_ for more details. [experimental manual](manual_experimental.html) for more details.
Example: Example:
@ -7449,7 +7443,7 @@ compiler like one would use the command-line switch `--passc`:option:\:
{.passc: "-Wall -Werror".} {.passc: "-Wall -Werror".}
``` ```
Note that one can use `gorge` from the `system module <system.html>`_ to Note that one can use `gorge` from the [system module](system.html) to
embed parameters from an external command that will be executed embed parameters from an external command that will be executed
during semantic analysis: during semantic analysis:
@ -7480,7 +7474,7 @@ like one would be using the command-line switch `--passl`:option:\:
{.passl: "-lSDLmain -lSDL".} {.passl: "-lSDLmain -lSDL".}
``` ```
Note that one can use `gorge` from the `system module <system.html>`_ to Note that one can use `gorge` from the [system module](system.html) to
embed parameters from an external command that will be executed embed parameters from an external command that will be executed
during semantic analysis: during semantic analysis:
@ -7553,13 +7547,13 @@ the code should be emitted can be influenced via the prefixes
ImportCpp pragma ImportCpp pragma
---------------- ----------------
**Note**: `c2nim <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ can parse a large subset of C++ and knows **Note**: [c2nim](https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst)
can parse a large subset of C++ and knows
about the `importcpp` pragma pattern language. It is not necessary about the `importcpp` pragma pattern language. It is not necessary
to know all the details described here. to know all the details described here.
Similar to the `importc pragma for C Similar to the [importc pragma] for C, the
<#foreign-function-interface-importc-pragma>`_, the
`importcpp` pragma can be used to import `C++`:idx: methods or C++ symbols `importcpp` pragma can be used to import `C++`:idx: methods or C++ symbols
in general. The generated code then uses the C++ method calling in general. The generated code then uses the C++ method calling
syntax: `obj->method(arg)`:cpp:. In combination with the `header` and `emit` syntax: `obj->method(arg)`:cpp:. In combination with the `header` and `emit`
@ -7791,7 +7785,7 @@ Produces:
ImportJs pragma ImportJs pragma
--------------- ---------------
Similar to the `importcpp pragma for C++ <#implementation-specific-pragmas-importcpp-pragma>`_, Similar to the [importcpp pragma] for C++,
the `importjs` pragma can be used to import Javascript methods or the `importjs` pragma can be used to import Javascript methods or
symbols in general. The generated code then uses the Javascript method symbols in general. The generated code then uses the Javascript method
calling syntax: ``obj.method(arg)``. calling syntax: ``obj.method(arg)``.
@ -7799,8 +7793,7 @@ calling syntax: ``obj.method(arg)``.
ImportObjC pragma ImportObjC pragma
----------------- -----------------
Similar to the `importc pragma for C Similar to the [importc pragma] for C, the `importobjc` pragma can
<#foreign-function-interface-importc-pragma>`_, the `importobjc` pragma can
be used to import `Objective C`:idx: methods. The generated code then uses the be used to import `Objective C`:idx: methods. The generated code then uses the
Objective C method calling syntax: ``[obj method param1: arg]``. Objective C method calling syntax: ``[obj method param1: arg]``.
In addition with the `header` and `emit` pragmas this In addition with the `header` and `emit` pragmas this
@ -8016,7 +8009,7 @@ definitions, statements, etc.
The macros module includes helpers which can be used to simplify custom pragma The macros module includes helpers which can be used to simplify custom pragma
access `hasCustomPragma`, `getCustomPragmaVal`. Please consult the access `hasCustomPragma`, `getCustomPragmaVal`. Please consult the
`macros <macros.html>`_ module documentation for details. These macros are not [macros](macros.html) module documentation for details. These macros are not
magic, everything they do can also be achieved by walking the AST of the object magic, everything they do can also be achieved by walking the AST of the object
representation. representation.
@ -8084,8 +8077,8 @@ the same way.
There are a few more applications of macro pragmas, such as in type, There are a few more applications of macro pragmas, such as in type,
variable and constant declarations, but this behavior is considered to be variable and constant declarations, but this behavior is considered to be
experimental and is documented in the `experimental manual experimental and is documented in the [experimental manual](
<manual_experimental.html#extended-macro-pragmas>`_ instead. manual_experimental.html#extended-macro-pragmas) instead.
Foreign function interface Foreign function interface
@ -8123,9 +8116,9 @@ JS backend for JS objects and functions. Other backends do provide
the same feature under the same name. Also, when the target language the same feature under the same name. Also, when the target language
is not set to C, other pragmas are available: is not set to C, other pragmas are available:
* `importcpp <manual.html#implementation-specific-pragmas-importcpp-pragma>`_ * [importcpp][importcpp pragma]
* `importobjc <manual.html#implementation-specific-pragmas-importobjc-pragma>`_ * [importobjc][importobjc pragma]
* `importjs <manual.html#implementation-specific-pragmas-importjs-pragma>`_ * [importjs][importjs pragma]
The string literal passed to `importc` can be a format string: The string literal passed to `importc` can be a format string:
@ -8163,7 +8156,7 @@ is available and a literal dollar sign must be written as ``$$``.
If the symbol should also be exported to a dynamic library, the `dynlib` If the symbol should also be exported to a dynamic library, the `dynlib`
pragma should be used in addition to the `exportc` pragma. See pragma should be used in addition to the `exportc` pragma. See
`Dynlib pragma for export <#foreign-function-interface-dynlib-pragma-for-export>`_. [Dynlib pragma for export].
Extern pragma Extern pragma
@ -8296,7 +8289,7 @@ because of order of initialization problems.
**Note**: A `dynlib` import can be overridden with **Note**: A `dynlib` import can be overridden with
the `--dynlibOverride:name`:option: command-line option. The the `--dynlibOverride:name`:option: command-line option. The
`Compiler User Guide <nimc.html>`_ contains further information. [Compiler User Guide](nimc.html) contains further information.
Dynlib pragma for export Dynlib pragma for export
@ -8319,10 +8312,10 @@ Threads
======= =======
To enable thread support the `--threads:on`:option: command-line switch needs to To enable thread support the `--threads:on`:option: command-line switch needs to
be used. The system_ module then contains several threading primitives. be used. The [system module](system.html) module then contains several threading primitives.
See the `channels <channels_builtin.html>`_ modules See the [channels](channels_builtin.html) 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 <manual_experimental.html#parallel-amp-spawn>`_ for available. See [spawn](manual_experimental.html#parallel-amp-spawn) for
further details. further details.
Nim's memory model for threads is quite different than that of other common Nim's memory model for threads is quite different than that of other common
@ -8452,7 +8445,8 @@ model low level lockfree mechanisms:
The `locks` pragma takes a list of lock expressions `locks: [a, b, ...]` The `locks` pragma takes a list of lock expressions `locks: [a, b, ...]`
in order to support *multi lock* statements. Why these are essential is in order to support *multi lock* statements. Why these are essential is
explained in the `lock levels <#guards-and-locks-lock-levels>`_ section. explained in the [lock levels](manual_experimental.md#lock-levels) section
of experimental manual.
### Protecting general locations ### Protecting general locations

View file

@ -233,7 +233,7 @@ from a module. The syntax `import foo {.all.}` can be used to import all
symbols from the module `foo`. Note that importing private symbols is symbols from the module `foo`. Note that importing private symbols is
generally not recommended. generally not recommended.
See also the experimental `importutils <importutils.html>`_ module. See also the experimental [importutils](importutils.html) module.
Code reordering Code reordering
@ -464,7 +464,7 @@ to use this operator.
Extended macro pragmas Extended macro pragmas
====================== ======================
Macro pragmas as described in `the manual <manual.html#userminusdefined-pragmas-macro-pragmas>`_ Macro pragmas as described in [the manual](manual.html#userminusdefined-pragmas-macro-pragmas)
can also be applied to type, variable and constant declarations. can also be applied to type, variable and constant declarations.
For types: For types:
@ -630,7 +630,7 @@ For example:
The algorithm behind this analysis is described in The algorithm behind this analysis is described in
the `view types section <#view-types-algorithm>`_. the [view types algorithm].
View types View types
@ -744,7 +744,7 @@ has `source` as the owner. A path expression `e` is defined recursively:
If a view type is used as a return type, the location must borrow from a location If a view type is used as a return type, the location must borrow from a location
that is derived from the first parameter that is passed to the proc. that is derived from the first parameter that is passed to the proc.
See `the manual <manual.html#procedures-var-return-type>`_ See [the manual](manual.html#procedures-var-return-type)
for details about how this is done for `var T`. for details about how this is done for `var T`.
A mutable view can borrow from a mutable location, an immutable view can borrow A mutable view can borrow from a mutable location, an immutable view can borrow
@ -785,7 +785,7 @@ The scope of the view does not matter:
The analysis requires as much precision about mutations as is reasonably obtainable, The analysis requires as much precision about mutations as is reasonably obtainable,
so it is more effective with the experimental `strict funcs <#strict-funcs>`_ so it is more effective with the experimental [strict funcs]
feature. In other words `--experimental:views`:option: works better feature. In other words `--experimental:views`:option: works better
with `--experimental:strictFuncs`:option:. with `--experimental:strictFuncs`:option:.
@ -1340,7 +1340,7 @@ object inheritance syntax involving the `of` keyword:
like channels, to implement thread safe automatic memory management. like channels, to implement thread safe automatic memory management.
The builtin `deepCopy` can even clone closures and their environments. See The builtin `deepCopy` can even clone closures and their environments. See
the documentation of `spawn <#parallel-amp-spawn-spawn-statement>`_ for details. the documentation of [spawn][spawn statement] for details.
Dynamic arguments for bindSym Dynamic arguments for bindSym
@ -1771,7 +1771,7 @@ Nim has two flavors of parallelism:
Nim has a builtin thread pool that can be used for CPU intensive tasks. For Nim has a builtin thread pool that can be used for CPU intensive tasks. For
IO intensive tasks the `async` and `await` features should be IO intensive tasks the `async` and `await` features should be
used instead. Both parallel and spawn need the `threadpool <threadpool.html>`_ used instead. Both parallel and spawn need the [threadpool](threadpool.html)
module to work. module to work.
Somewhat confusingly, `spawn` is also used in the `parallel` statement Somewhat confusingly, `spawn` is also used in the `parallel` statement

View file

@ -21,7 +21,7 @@ Attempting to declare a set with a larger type will result in an error:
``` ```
**Note:** Nim also offers `hash sets <sets.html>`_ (which you need to import **Note:** Nim also offers [hash sets](sets.html) (which you need to import
with `import sets`), which have no such restrictions. with `import sets`), which have no such restrictions.
Sets can be constructed via the set constructor: `{}` is the empty set. The Sets can be constructed via the set constructor: `{}` is the empty set. The
@ -90,4 +90,4 @@ Note how the set turns enum values into powers of 2.
If using enums and sets with C, use distinct cint. If using enums and sets with C, use distinct cint.
For interoperability with C see also the For interoperability with C see also the
`bitsize pragma <manual.html#implementation-specific-pragmas-bitsize-pragma>`_. [bitsize pragma](manual.html#implementation-specific-pragmas-bitsize-pragma).

View file

@ -22,14 +22,14 @@ like variables, types, or statements.
Here are several other resources for learning Nim: Here are several other resources for learning Nim:
* `Nim Basics tutorial <https://narimiran.github.io/nim-basics/>`_ - a gentle * [Nim Basics tutorial](https://narimiran.github.io/nim-basics/) - a gentle
introduction of the concepts mentioned above introduction of the concepts mentioned above
* `Learn Nim in 5 minutes <https://learnxinyminutes.com/docs/nim/>`_ - quick, * [Learn Nim in 5 minutes](https://learnxinyminutes.com/docs/nim/) - quick,
five-minute introduction to Nim five-minute introduction to Nim
* `The Nim manual <manual.html>`_ - many more examples of the advanced language features * [The Nim manual](manual.html) - many more examples of the advanced language features
All code examples in this tutorial, as well as the ones found in the rest of All code examples in this tutorial, as well as the ones found in the rest of
Nim's documentation, follow the `Nim style guide <nep1.html>`_. Nim's documentation, follow the [Nim style guide](nep1.html).
The first program The first program
@ -49,7 +49,7 @@ Save this code to the file "greetings.nim". Now compile and run it::
nim compile --run greetings.nim nim compile --run greetings.nim
With the ``--run`` `switch <nimc.html#compiler-usage-commandminusline-switches>`_ Nim With the ``--run`` [switch](nimc.html#compiler-usage-commandminusline-switches) Nim
executes the file automatically after compilation. You can give your program executes the file automatically after compilation. You can give your program
command-line arguments by appending them after the filename:: command-line arguments by appending them after the filename::
@ -66,8 +66,8 @@ To compile a release version use::
By default, the Nim compiler generates a large number of runtime checks By default, the Nim compiler generates a large number of runtime checks
aiming for your debugging pleasure. With ``-d:release`` some checks are aiming for your debugging pleasure. With ``-d:release`` some checks are
`turned off and optimizations are turned on [turned off and optimizations are turned on](
<nimc.html#compiler-usage-compileminustime-symbols>`_. nimc.html#compiler-usage-compileminustime-symbols).
For benchmarking or production code, use the ``-d:release`` switch. For benchmarking or production code, use the ``-d:release`` switch.
For comparing the performance with unsafe languages like C, use the ``-d:danger`` switch For comparing the performance with unsafe languages like C, use the ``-d:danger`` switch
@ -81,8 +81,8 @@ done with spaces only, tabulators are not allowed.
String literals are enclosed in double-quotes. The `var` statement declares String literals are enclosed in double-quotes. The `var` statement declares
a new variable named `name` of type `string` with the value that is a new variable named `name` of type `string` with the value that is
returned by the `readLine <syncio.html#readLine,File>`_ procedure. Since the returned by the [readLine](syncio.html#readLine,File) procedure. Since the
compiler knows that `readLine <syncio.html#readLine,File>`_ returns a string, compiler knows that [readLine](syncio.html#readLine,File) returns a string,
you can leave out the type in the declaration (this is called `local type you can leave out the type in the declaration (this is called `local type
inference`:idx:). So this will work too: inference`:idx:). So this will work too:
@ -94,8 +94,8 @@ Note that this is basically the only form of type inference that exists in
Nim: it is a good compromise between brevity and readability. Nim: it is a good compromise between brevity and readability.
The "hello world" program contains several identifiers that are already known The "hello world" program contains several identifiers that are already known
to the compiler: `echo`, `readLine <syncio.html#readLine,File>`_, etc. to the compiler: `echo`, [readLine](syncio.html#readLine,File), etc.
These built-ins are declared in the system_ module which is implicitly These built-ins are declared in the [system](system.html) module which is implicitly
imported by any other module. imported by any other module.
@ -340,7 +340,7 @@ the compiler that for every other value nothing should be done:
else: discard else: discard
``` ```
The empty `discard statement <#procedures-discard-statement>`_ is a *do The empty [discard statement] is a *do
nothing* statement. The compiler knows that a case statement with an else part nothing* statement. The compiler knows that a case statement with an else part
cannot fail and thus the error disappears. Note that it is impossible to cover cannot fail and thus the error disappears. Note that it is impossible to cover
all possible string values: that is why string cases always need an `else` all possible string values: that is why string cases always need an `else`
@ -372,8 +372,8 @@ For statement
------------- -------------
The `for` statement is a construct to loop over any element an *iterator* The `for` statement is a construct to loop over any element an *iterator*
provides. The example uses the built-in `countup provides. The example uses the built-in [countup](
<system.html#countup.i,T,T,Positive>`_ iterator: system.html#countup.i,T,T,Positive) iterator:
```nim test = "nim c $1" ```nim test = "nim c $1"
echo "Counting to ten: " echo "Counting to ten: "
@ -383,8 +383,8 @@ provides. The example uses the built-in `countup
``` ```
The variable `i` is implicitly declared by the The variable `i` is implicitly declared by the
`for` loop and has the type `int`, because that is what `countup `for` loop and has the type `int`, because that is what [countup](
<system.html#countup.i,T,T,Positive>`_ returns. `i` runs through the values system.html#countup.i,T,T,Positive) returns. `i` runs through the values
1, 2, .., 10. Each value is `echo`-ed. This code does the same: 1, 2, .., 10. Each value is `echo`-ed. This code does the same:
```nim ```nim
@ -396,8 +396,8 @@ The variable `i` is implicitly declared by the
# --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines
``` ```
Since counting up occurs so often in programs, Nim also has a `.. Since counting up occurs so often in programs, Nim also has a [..](
<system.html#...i,T,T>`_ iterator that does the same: system.html#...i,T,T) iterator that does the same:
```nim ```nim
for i in 1 .. 10: for i in 1 .. 10:
@ -414,7 +414,7 @@ Counting down can be achieved as easily (but is less often needed):
``` ```
Zero-indexed counting has two shortcuts `..<` and `.. ^1` Zero-indexed counting has two shortcuts `..<` and `.. ^1`
(`backward index operator <system.html#^.t%2Cint>`_) to simplify ([backward index operator](system.html#^.t%2Cint)) to simplify
counting to one less than the higher index: counting to one less than the higher index:
```nim ```nim
@ -600,11 +600,11 @@ an expression is allowed:
Procedures Procedures
========== ==========
To define new commands like `echo <system.html#echo,varargs[typed,]>`_ To define new commands like [echo](system.html#echo,varargs[typed,])
and `readLine <syncio.html#readLine,File>`_ in the examples, the concept of a and [readLine](syncio.html#readLine,File) in the examples, the concept of a
*procedure* is needed. You might be used to them being called *methods* or *procedure* is needed. You might be used to them being called *methods* or
*functions* in other languages, but Nim *functions* in other languages, but Nim
`differentiates these concepts <tut1.html#procedures-funcs-and-methods>`_. In [differentiates these concepts](tut1.html#procedures-funcs-and-methods). In
Nim, new procedures are defined with the `proc` keyword: Nim, new procedures are defined with the `proc` keyword:
```nim test = "nim c $1" ```nim test = "nim c $1"
@ -808,7 +808,7 @@ Nim provides the ability to overload procedures similar to C++:
assert toString(true) == "yep" # calls the toString(x: bool) proc assert toString(true) == "yep" # calls the toString(x: bool) proc
``` ```
(Note that `toString` is usually the `$ <dollars.html>`_ operator in (Note that `toString` is usually the [$](dollars.html) operator in
Nim.) The compiler chooses the most appropriate proc for the `toString` Nim.) The compiler chooses the most appropriate proc for the `toString`
calls. How this overloading resolution algorithm works exactly is not calls. How this overloading resolution algorithm works exactly is not
discussed here -- see the manual for details. Ambiguous calls are reported as errors. discussed here -- see the manual for details. Ambiguous calls are reported as errors.
@ -833,7 +833,7 @@ User-defined operators are allowed. Nothing stops you from defining your own
`@!?+~` operator, but doing so may reduce readability. `@!?+~` operator, but doing so may reduce readability.
The operator's precedence is determined by its first character. The details The operator's precedence is determined by its first character. The details
can be `found in the manual <manual.html#syntax-precedence>`_. can be [found in the manual](manual.html#syntax-precedence).
To define a new operator enclose the operator in backticks "`": To define a new operator enclose the operator in backticks "`":
@ -882,7 +882,7 @@ Here `odd` depends on `even` and vice versa. Thus `even` needs to be
introduced to the compiler before it is completely defined. The syntax for introduced to the compiler before it is completely defined. The syntax for
such a forward declaration is simple: just omit the `=` and the such a forward declaration is simple: just omit the `=` and the
procedure's body. The `assert` just adds border conditions, and will be procedure's body. The `assert` just adds border conditions, and will be
covered later in `Modules`_ section. covered later in [Modules] section.
Later versions of the language will weaken the requirements for forward Later versions of the language will weaken the requirements for forward
declarations. declarations.
@ -913,7 +913,7 @@ programming. If you overload a procedure (two procedures with the same name but
of different types or with different sets of arguments are said to be overloaded), the procedure to use is determined of different types or with different sets of arguments are said to be overloaded), the procedure to use is determined
at compile-time. Methods, on the other hand, depend on objects that inherit from at compile-time. Methods, on the other hand, depend on objects that inherit from
the `RootObj`. This is something that is covered in much greater depth in the `RootObj`. This is something that is covered in much greater depth in
the `second part of the tutorial<tut2.html#object-oriented-programming-dynamic-dispatch>`_. the [second part of the tutorial](tut2.html#object-oriented-programming-dynamic-dispatch).
Iterators Iterators
@ -927,7 +927,7 @@ Let's return to the simple counting example:
echo i echo i
``` ```
Can a `countup <system.html#countup.i,T,T,Positive>`_ proc be written that Can a [countup](system.html#countup.i,T,T,Positive) proc be written that
supports this loop? Let's try: supports this loop? Let's try:
```nim ```nim
@ -964,12 +964,13 @@ important differences:
(This restriction will be gone in a future version of the compiler.) (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 However, you can also use a closure iterator to get a different set of
restrictions. See `first-class iterators <manual.html#iterators-and-the-for-statement-firstminusclass-iterators>`_ restrictions. See [first-class iterators](
manual.html#iterators-and-the-for-statement-firstminusclass-iterators)
for details. Iterators can have the same name and parameters as a proc since for details. Iterators can have the same name and parameters as a proc since
essentially they have their own namespaces. Therefore, it is common to essentially they have their own namespaces. Therefore, it is common to
wrap iterators in procs of the same name which accumulate the result of the wrap iterators in procs of the same name which accumulate the result of the
iterator and return it as a sequence, like `split` from the `strutils module iterator and return it as a sequence, like `split` from the [strutils module](
<strutils.html>`_. strutils.html).
Basic types Basic types
@ -1095,8 +1096,8 @@ 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 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 types are **not** converted to floating-point types automatically, nor vice
versa. Use the `toInt <system.html#toInt,float>`_ and versa. Use the [toInt](system.html#toInt,float) and
`toFloat <system.html#toFloat,int>`_ procs for these conversions. [toFloat](system.html#toFloat,int) procs for these conversions.
Type Conversion Type Conversion
@ -1117,13 +1118,13 @@ type as a function:
Internal type representation Internal type representation
============================ ============================
As mentioned earlier, the built-in `$ <dollars.html>`_ (stringify) operator As mentioned earlier, the built-in [$](dollars.html) (stringify) operator
turns any basic type into a string, which you can then print to the console turns any basic type into a string, which you can then print to the console
using the `echo` proc. However, advanced types, and your own custom types, using the `echo` proc. However, advanced types, and your own custom types,
won't work with the `$` operator until you define it for them. won't work with the `$` operator until you define it for them.
Sometimes you just want to debug the current value of a complex type without Sometimes you just want to debug the current value of a complex type without
having to write its `$` operator. You can use then the `repr having to write its `$` operator. You can use then the [repr](
<system.html#repr,T>`_ proc which works with any type and even complex data system.html#repr,T) proc which works with any type and even complex data
graphs with cycles. The following example shows that even for basic types graphs with cycles. The following example shows that even for basic types
there is a difference between the `$` and `repr` outputs: there is a difference between the `$` and `repr` outputs:
@ -1216,8 +1217,8 @@ Operation Comment
================= ======================================================== ================= ========================================================
The `inc <system.html#inc,T,int>`_, `dec <system.html#dec,T,int>`_, `succ The [inc](system.html#inc,T,int), [dec](system.html#dec,T,int), [succ](
<system.html#succ,T,int>`_ and `pred <system.html#pred,T,int>`_ operations can system.html#succ,T,int) and [pred](system.html#pred,T,int) operations can
fail by raising an `RangeDefect` or `OverflowDefect`. (If the code has been fail by raising an `RangeDefect` or `OverflowDefect`. (If the code has been
compiled with the proper runtime checks turned on.) compiled with the proper runtime checks turned on.)
@ -1239,8 +1240,8 @@ to 5. Assigning any other value to a variable of type `MySubrange` is a
compile-time or runtime error. Assignments from the base type to one of its compile-time or runtime error. Assignments from the base type to one of its
subrange types (and vice versa) are allowed. subrange types (and vice versa) are allowed.
The `system` module defines the important `Natural <system.html#Natural>`_ The `system` module defines the important [Natural](system.html#Natural)
type as `range[0..high(int)]` (`high <system.html#high,typedesc[T]>`_ returns type as `range[0..high(int)]` ([high](system.html#high,typedesc[T]) returns
the maximal value). Other programming languages may suggest the use of unsigned the maximal value). Other programming languages may suggest the use of unsigned
integers for natural numbers. This is often **unwise**: you don't want unsigned integers for natural numbers. This is often **unwise**: you don't want unsigned
arithmetic (which wraps around) just because the numbers cannot be negative. arithmetic (which wraps around) just because the numbers cannot be negative.
@ -1278,9 +1279,9 @@ checks can be disabled via pragmas or invoking the compiler with the
Arrays are value types, like any other Nim type. The assignment operator Arrays are value types, like any other Nim type. The assignment operator
copies the whole array contents. copies the whole array contents.
The built-in `len <system.html#len,TOpenArray>`_ proc returns the array's The built-in [len](system.html#len,TOpenArray) proc returns the array's
length. `low(a) <system.html#low,openArray[T]>`_ returns the lowest valid index length. [low(a)](system.html#low,openArray[T]) returns the lowest valid index
for the array `a` and `high(a) <system.html#high,openArray[T]>`_ the highest for the array `a` and [high(a)](system.html#high,openArray[T]) the highest
valid index. valid index.
```nim test = "nim c $1" ```nim test = "nim c $1"
@ -1358,14 +1359,14 @@ Sequences are similar to arrays but of dynamic length which may change
during runtime (like strings). Since sequences are resizable they are always during runtime (like strings). Since sequences are resizable they are always
allocated on the heap and garbage collected. allocated on the heap and garbage collected.
Sequences are always indexed with an `int` starting at position 0. The `len Sequences are always indexed with an `int` starting at position 0. The [len](
<system.html#len,seq[T]>`_, `low <system.html#low,openArray[T]>`_ and `high system.html#len,seq[T]), [low](system.html#low,openArray[T]) and [high](
<system.html#high,openArray[T]>`_ operations are available for sequences too. system.html#high,openArray[T]) operations are available for sequences too.
The notation `x[i]` can be used to access the i-th element of `x`. The notation `x[i]` can be used to access the i-th element of `x`.
Sequences can be constructed by the array constructor `[]` in conjunction Sequences can be constructed by the array constructor `[]` in conjunction
with the array to sequence operator `@`. Another way to allocate space for with the array to sequence operator `@`. Another way to allocate space for
a sequence is to call the built-in `newSeq <system.html#newSeq>`_ procedure. a sequence is to call the built-in [newSeq](system.html#newSeq) procedure.
A sequence may be passed to an openarray parameter. A sequence may be passed to an openarray parameter.
@ -1382,12 +1383,12 @@ Sequence variables are initialized with `@[]`.
The `for` statement can be used with one or two variables when used with a The `for` statement can be used with one or two variables when used with a
sequence. When you use the one variable form, the variable will hold the value sequence. When you use the one variable form, the variable will hold the value
provided by the sequence. The `for` statement is looping over the results provided by the sequence. The `for` statement is looping over the results
from the `items() <iterators.html#items.i,seq[T]>`_ iterator from the `system from the [items()](iterators.html#items.i,seq[T]) iterator from the [system](
<system.html>`_ module. But if you use the two-variable form, the first system.html) module. But if you use the two-variable form, the first
variable will hold the index position and the second variable will hold the variable will hold the index position and the second variable will hold the
value. Here the `for` statement is looping over the results from the value. Here the `for` statement is looping over the results from the
`pairs() <iterators.html#pairs.i,seq[T]>`_ iterator from the `system [pairs()](iterators.html#pairs.i,seq[T]) iterator from the [system](
<system.html>`_ module. Examples: system.html) module. Examples:
```nim test = "nim c $1" ```nim test = "nim c $1"
for value in @[3, 4, 5]: for value in @[3, 4, 5]:
@ -1412,8 +1413,8 @@ Open arrays
Often fixed-size arrays turn out to be too inflexible; procedures should be Often fixed-size arrays turn out to be too inflexible; procedures should be
able to deal with arrays of different sizes. The `openarray`:idx: type allows able to deal with arrays of different sizes. The `openarray`:idx: type allows
this. Openarrays are always indexed with an `int` starting at position 0. this. Openarrays are always indexed with an `int` starting at position 0.
The `len <system.html#len,TOpenArray>`_, `low <system.html#low,openArray[T]>`_ The [len](system.html#len,TOpenArray), [low](system.html#low,openArray[T])
and `high <system.html#high,openArray[T]>`_ operations are available for open and [high](system.html#high,openArray[T]) operations are available for open
arrays too. Any array with a compatible base type can be passed to an arrays too. Any array with a compatible base type can be passed to an
openarray parameter, the index type does not matter. openarray parameter, the index type does not matter.
@ -1471,8 +1472,8 @@ type conversions in this context:
myWriteln(stdout, [$123, $"abc", $4.0]) myWriteln(stdout, [$123, $"abc", $4.0])
``` ```
In this example `$ <dollars.html>`_ is applied to any argument that is passed In this example [$](dollars.html) is applied to any argument that is passed
to the parameter `a`. Note that `$ <dollars.html>`_ applied to strings is a to the parameter `a`. Note that [$](dollars.html) applied to strings is a
nop. nop.
@ -1515,7 +1516,7 @@ indices are
where `b[0 .. ^1]` is equivalent to `b[0 .. b.len-1]` and `b[0 ..< b.len]`, and it where `b[0 .. ^1]` is equivalent to `b[0 .. b.len-1]` and `b[0 ..< b.len]`, and it
can be seen that the `^1` provides a shorthand way of specifying the `b.len-1`. See can be seen that the `^1` provides a shorthand way of specifying the `b.len-1`. See
the `backwards index operator <system.html#^.t%2Cint>`_. the [backwards index operator](system.html#^.t%2Cint).
In the above example, because the string ends in a period, to get the portion of the In the above example, because the string ends in a period, to get the portion of the
string that is "useless" and replace it with "useful". string that is "useless" and replace it with "useful".
@ -1526,7 +1527,7 @@ string that is "useless" and replace it with "useful".
Note 1: alternate ways of writing this are `b[^8 .. ^2] = "useful"` or Note 1: alternate ways of writing this are `b[^8 .. ^2] = "useful"` or
as `b[11 .. b.len-2] = "useful"` or as `b[11 ..< b.len-1] = "useful"`. as `b[11 .. b.len-2] = "useful"` or as `b[11 ..< b.len-1] = "useful"`.
Note 2: As the `^` template returns a `distinct int <manual.html#types-distinct-type>`_ Note 2: As the `^` template returns a [distinct int](manual.html#types-distinct-type)
of type `BackwardsIndex`, we can have a `lastIndex` constant defined as `const lastIndex = ^1`, of type `BackwardsIndex`, we can have a `lastIndex` constant defined as `const lastIndex = ^1`,
and later used as `b[0 .. lastIndex]`. and later used as `b[0 .. lastIndex]`.
@ -1659,8 +1660,8 @@ having the same field types.
Tuples can be *unpacked* during variable assignment. This can Tuples can be *unpacked* during variable assignment. This can
be handy to assign directly the fields of the tuples to individually named be handy to assign directly the fields of the tuples to individually named
variables. An example of this is the `splitFile <os.html#splitFile,string>`_ variables. An example of this is the [splitFile](os.html#splitFile,string)
proc from the `os module <os.html>`_ which returns the directory, name, and proc from the [os module](os.html) which returns the directory, name, and
extension of a path at the same time. For tuple unpacking to work you must extension of a path at the same time. For tuple unpacking to work you must
use parentheses around the values you want to assign the unpacking to, use parentheses around the values you want to assign the unpacking to,
otherwise, you will be assigning the same value to all the individual otherwise, you will be assigning the same value to all the individual
@ -1743,7 +1744,7 @@ To allocate a new traced object, the built-in procedure `new` can be used:
``` ```
To deal with untraced memory, the procedures `alloc`, `dealloc` and To deal with untraced memory, the procedures `alloc`, `dealloc` and
`realloc` can be used. The `system <system.html>`_ `realloc` can be used. The [system](system.html)
module's documentation contains further details. module's documentation contains further details.
If a reference points to *nothing*, it has the value `nil`. If a reference points to *nothing*, it has the value `nil`.
@ -1776,7 +1777,7 @@ Example:
A subtle issue with procedural types is that the calling convention of the A subtle issue with procedural types is that the calling convention of the
procedure influences the type compatibility: procedural types are only compatible procedure influences the type compatibility: procedural types are only compatible
if they have the same calling convention. The different calling conventions are if they have the same calling convention. The different calling conventions are
listed in the `manual <manual.html#types-procedural-type>`_. listed in the [manual](manual.html#types-procedural-type).
Distinct type Distinct type
------------- -------------
@ -1786,7 +1787,7 @@ subtype relationship between it and its base type".
You must **explicitly** define all behavior for the distinct type. You must **explicitly** define all behavior for the distinct type.
To help with this, both the distinct type and its base type can cast from one To help with this, both the distinct type and its base type can cast from one
type to the other. type to the other.
Examples are provided in the `manual <manual.html#types-distinct-type>`_. Examples are provided in the [manual](manual.html#types-distinct-type).
Modules Modules
======= =======
@ -1940,7 +1941,7 @@ Part 2
====== ======
So, now that we are done with the basics, let's see what Nim offers apart So, now that we are done with the basics, let's see what Nim offers apart
from a nice syntax for procedural programming: `Part II <tut2.html>`_ from a nice syntax for procedural programming: [Part II](tut2.html)
.. _strutils: strutils.html .. _strutils: strutils.html

View file

@ -17,7 +17,7 @@ Introduction
This document is a tutorial for the advanced constructs of the *Nim* This document is a tutorial for the advanced constructs of the *Nim*
programming language. **Note that this document is somewhat obsolete as the** programming language. **Note that this document is somewhat obsolete as the**
`manual <manual.html>`_ **contains many more examples of the advanced language [manual](manual.html) **contains many more examples of the advanced language
features.** features.**
@ -27,8 +27,8 @@ Pragmas
Pragmas are Nim's method to give the compiler additional information/ Pragmas are Nim's method to give the compiler additional information/
commands without introducing a massive number of new keywords. Pragmas are commands without introducing a massive number of new keywords. Pragmas are
enclosed in the special `{.` and `.}` curly dot brackets. This tutorial enclosed in the special `{.` and `.}` curly dot brackets. This tutorial
does not cover pragmas. See the `manual <manual.html#pragmas>`_ or `user guide does not cover pragmas. See the [manual](manual.html#pragmas) or [user guide](
<nimc.html#additional-features>`_ for a description of the available nimc.html#additional-features) for a description of the available
pragmas. pragmas.
@ -337,7 +337,7 @@ Exceptions
========== ==========
In Nim exceptions are objects. By convention, exception types are In Nim exceptions are objects. By convention, exception types are
suffixed with 'Error'. The `system <system.html>`_ module defines an suffixed with 'Error'. The [system](system.html) module defines an
exception hierarchy that you might want to stick to. Exceptions derive from exception hierarchy that you might want to stick to. Exceptions derive from
`system.Exception`, which provides the common interface. `system.Exception`, which provides the common interface.
@ -417,9 +417,9 @@ the rest of the procedure - that is not within a `finally` clause -
is not executed (if an exception occurs). is not executed (if an exception occurs).
If you need to *access* the actual exception object or message inside an If you need to *access* the actual exception object or message inside an
`except` branch you can use the `getCurrentException() `except` branch you can use the [getCurrentException()](
<system.html#getCurrentException>`_ and `getCurrentExceptionMsg() system.html#getCurrentException) and [getCurrentExceptionMsg()](
<system.html#getCurrentExceptionMsg>`_ procs from the `system <system.html>`_ system.html#getCurrentExceptionMsg) procs from the [system](system.html)
module. Example: module. Example:
```nim ```nim
@ -464,7 +464,7 @@ tracking is part of Nim's effect system). Another more roundabout way to
find out the list of exceptions raised by a proc is to use the Nim ``doc`` find out the list of exceptions raised by a proc is to use the Nim ``doc``
command which generates documentation for a whole module and decorates all command which generates documentation for a whole module and decorates all
procs with the list of raised exceptions. You can read more about Nim's procs with the list of raised exceptions. You can read more about Nim's
`effect system and related pragmas in the manual <manual.html#effect-system>`_. [effect system and related pragmas in the manual](manual.html#effect-system).
Generics Generics
@ -694,4 +694,4 @@ JavaScript-compatible code you should remember the following:
Part 3 Part 3
====== ======
The next part is entirely about metaprogramming via macros: `Part III <tut3.html>`_ The next part is entirely about metaprogramming via macros: [Part III](tut3.html).

View file

@ -125,7 +125,7 @@ The Syntax Tree
In order to build a Nim syntax tree one needs to know how Nim source In order to build a Nim syntax tree one needs to know how Nim source
code is represented as a syntax tree, and how such a tree needs to code is represented as a syntax tree, and how such a tree needs to
look like so that the Nim compiler will understand it. The nodes of the look like so that the Nim compiler will understand it. The nodes of the
Nim syntax tree are documented in the `macros <macros.html>`_ module. Nim syntax tree are documented in the [macros](macros.html) module.
But a more interactive way to explore the Nim But a more interactive way to explore the Nim
syntax tree is with `macros.treeRepr`, it converts a syntax tree syntax tree is with `macros.treeRepr`, it converts a syntax tree
into a multi-line string for printing on the console. It can be used into a multi-line string for printing on the console. It can be used
@ -366,7 +366,7 @@ recommended way. But still `strformat` is a good example for a
practical use case for a macro that is slightly more complex than the practical use case for a macro that is slightly more complex than the
`assert` macro. `assert` macro.
`Strformat <https://github.com/nim-lang/Nim/blob/5845716df8c96157a047c2bd6bcdd795a7a2b9b1/lib/pure/strformat.nim#L280>`_ [Strformat](https://github.com/nim-lang/Nim/blob/5845716df8c96157a047c2bd6bcdd795a7a2b9b1/lib/pure/strformat.nim#L280)
Ast Pattern Matching Ast Pattern Matching
-------------------- --------------------
@ -375,7 +375,7 @@ Ast Pattern Matching is a macro library to aid in writing complex
macros. This can be seen as a good example of how to repurpose the macros. This can be seen as a good example of how to repurpose the
Nim syntax tree with new semantics. Nim syntax tree with new semantics.
`Ast Pattern Matching <https://github.com/krux02/ast-pattern-matching>`_ [Ast Pattern Matching](https://github.com/krux02/ast-pattern-matching)
OpenGL Sandbox OpenGL Sandbox
-------------- --------------
@ -384,4 +384,4 @@ This project has a working Nim to GLSL compiler written entirely in
macros. It scans recursively through all used function symbols to macros. It scans recursively through all used function symbols to
compile them so that cross library functions can be executed on the GPU. compile them so that cross library functions can be executed on the GPU.
`OpenGL Sandbox <https://github.com/krux02/opengl-sandbox>`_ [OpenGL Sandbox](https://github.com/krux02/opengl-sandbox)

View file

@ -3578,7 +3578,7 @@ proc resolveLink(s: PRstSharedState, n: PRstNode) : PRstNode =
target: newLeaf(subst.refname), target: newLeaf(subst.refname),
info: subst.info, tooltip: subst.tooltip) info: subst.info, tooltip: subst.tooltip)
foundLinks.sort(cmp = cmp, order = Descending) foundLinks.sort(cmp = cmp, order = Descending)
let linkText = addNodes(desc) let aliasStr = addNodes(alias)
if foundLinks.len >= 1: if foundLinks.len >= 1:
let kind = if foundLinks[0].ar == arHyperlink: rnHyperlink let kind = if foundLinks[0].ar == arHyperlink: rnHyperlink
elif foundLinks[0].ar == arNim: rnNimdocRef elif foundLinks[0].ar == arNim: rnNimdocRef
@ -3598,10 +3598,10 @@ proc resolveLink(s: PRstSharedState, n: PRstNode) : PRstNode =
targets.add t targets.add t
rstMessage(s.filenames, s.msgHandler, n.info, mwAmbiguousLink, rstMessage(s.filenames, s.msgHandler, n.info, mwAmbiguousLink,
"`$1`\n clash:\n$2" % [ "`$1`\n clash:\n$2" % [
linkText, targets.join("\n")]) aliasStr, targets.join("\n")])
else: # nothing found else: # nothing found
result = n result = n
rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, linkText) rstMessage(s.filenames, s.msgHandler, n.info, mwBrokenLink, aliasStr)
proc resolveSubs*(s: PRstSharedState, n: PRstNode): PRstNode = proc resolveSubs*(s: PRstSharedState, n: PRstNode): PRstNode =
## Makes pass 2 of RST parsing. ## Makes pass 2 of RST parsing.

View file

@ -1181,6 +1181,22 @@ suite "Warnings":
"input(9, 6) Warning: broken link 'short.link'" "input(9, 6) Warning: broken link 'short.link'"
]) ])
test "Pandoc Markdown concise link warning points to target":
var warnings = new seq[string]
check(
"ref [here][target]".toAst(warnings=warnings) ==
dedent"""
rnInner
rnLeaf 'ref'
rnLeaf ' '
rnPandocRef
rnInner
rnLeaf 'here'
rnInner
rnLeaf 'target'
""")
check warnings[] == @["input(1, 12) Warning: broken link 'target'"]
test "With include directive and blank lines at the beginning": test "With include directive and blank lines at the beginning":
"other.rst".writeFile(dedent""" "other.rst".writeFile(dedent"""