diff options
Diffstat (limited to 'doc')
-rw-r--r-- | doc/grammar.txt | 2 | ||||
-rw-r--r-- | doc/lib.txt | 47 | ||||
-rw-r--r-- | doc/manual/lexing.txt | 2 | ||||
-rw-r--r-- | doc/manual/stmts.txt | 74 | ||||
-rw-r--r-- | doc/manual/syntax.txt | 17 | ||||
-rw-r--r-- | doc/manual/type_bound_ops.txt | 4 | ||||
-rw-r--r-- | doc/nimc.txt | 40 | ||||
-rw-r--r-- | doc/nimsuggest.txt | 174 | ||||
-rw-r--r-- | doc/tools.txt | 5 | ||||
-rw-r--r-- | doc/tut1.txt | 72 |
10 files changed, 323 insertions, 114 deletions
diff --git a/doc/grammar.txt b/doc/grammar.txt index b53515495..72dc6c974 100644 --- a/doc/grammar.txt +++ b/doc/grammar.txt @@ -179,7 +179,7 @@ simpleStmt = ((returnStmt | raiseStmt | yieldStmt | discardStmt | breakStmt | continueStmt | pragmaStmt | importStmt | exportStmt | fromStmt | includeStmt | commentStmt) / exprStmt) COMMENT? complexOrSimpleStmt = (ifStmt | whenStmt | whileStmt - | tryStmt | finallyStmt | exceptStmt | forStmt + | tryStmt | forStmt | blockStmt | staticStmt | deferStmt | asmStmt | 'proc' routine | 'method' routine diff --git a/doc/lib.txt b/doc/lib.txt index 385e7a91a..1c0278068 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -37,7 +37,7 @@ Core * `unsigned <unsigned.html>`_ This module implements basic arithmetic operators for unsigned integers. - To discourage users from using unsigned integers, it's not part + To discourage users from using unsigned integers, it's not part of ``system``, but an extra import. * `threads <threads.html>`_ @@ -45,7 +45,7 @@ Core import it explicitly. * `channels <channels.html>`_ - Nim message passing support for threads. **Note**: This is part of the + Nim message passing support for threads. **Note**: This is part of the system module. Do not import it explicitly. * `locks <locks.html>`_ @@ -55,7 +55,7 @@ Core Contains the AST API and documentation of Nim for writing macros. * `typeinfo <typeinfo.html>`_ - Provides (unsafe) access to Nim's run time type information. + Provides (unsafe) access to Nim's run time type information. * `typetraits <typetraits.html>`_ This module defines compile-time reflection procs for working with types. @@ -110,9 +110,9 @@ String handling * `unicode <unicode.html>`_ This module provides support to handle the Unicode UTF-8 encoding. - + * `encodings <encodings.html>`_ - Converts between different character encodings. On UNIX, this uses + Converts between different character encodings. On UNIX, this uses the ``iconv`` library, on Windows the Windows API. * `pegs <pegs.html>`_ @@ -159,7 +159,7 @@ Generic Operating System Services may provide other implementations for this standard stream interface. * `marshal <marshal.html>`_ - Contains procs for serialization and deseralization of arbitrary Nim + Contains procs for serialization and deseralization of arbitrary Nim data structures. * `terminal <terminal.html>`_ @@ -168,7 +168,7 @@ Generic Operating System Services sequences and does not depend on any other module. * `memfiles <memfiles.html>`_ - This module provides support for memory mapped files (Posix's ``mmap``) + This module provides support for memory mapped files (Posix's ``mmap``) on the different operating systems. * `fsmonitor <fsmonitor.html>`_ @@ -228,7 +228,7 @@ Internet Protocols and Support This module implements a simple HTTP client. * `smtp <smtp.html>`_ - This module implement a simple SMTP client. + This module implement a simple SMTP client. * `ftpclient <ftpclient.html>`_ This module implements an FTP client. @@ -346,7 +346,7 @@ XML Processing This module parses an HTML document and creates its XML tree representation. * `htmlgen <htmlgen.html>`_ - This module implements a simple XML and HTML code + This module implements a simple XML and HTML code generator. Each commonly used HTML tag has a corresponding macro that generates a string with its HTML representation. @@ -381,7 +381,7 @@ Miscellaneous * `oids <oids.html>`_ An OID is a global ID that consists of a timestamp, - a unique counter and a random value. This combination should suffice to + a unique counter and a random value. This combination should suffice to produce a globally distributed unique ID. This implementation was extracted from the Mongodb interface and it thus binary compatible with a Mongo OID. @@ -453,12 +453,8 @@ Other * `zipfiles <zipfiles.html>`_ This module implements a zip archive creator/reader/modifier. -* `web <web.html>`_ - This module contains simple high-level procedures for dealing with the - Web like loading the contents of a Web page from an URL. - * `ssl <ssl.html>`_ - This module provides an easy to use sockets-style + This module provides an easy to use sockets-style Nim interface to the OpenSSL library. * `rdstdin <rdstdin.html>`_ @@ -513,25 +509,6 @@ Regular expressions Wrapper for the TRE library. -Graphics libraries ------------------- - -* `sdl <sdl.html>`_ - Part of the wrapper for SDL. -* `sdl_gfx <sdl_gfx.html>`_ - Part of the wrapper for SDL. -* `sdl_image <sdl_image.html>`_ - Part of the wrapper for SDL. -* `sdl_mixer <sdl_mixer.html>`_ - Part of the wrapper for SDL. -* `sdl_net <sdl_net.html>`_ - Part of the wrapper for SDL. -* `sdl_ttf <sdl_ttf.html>`_ - Part of the wrapper for SDL. -* `smpeg <smpeg.html>`_ - Part of the wrapper for SDL. - - GUI libraries ------------- @@ -591,7 +568,7 @@ Data Compression and Archiving Scientific computing -------------------- -* `libsvm <libsvm.html>`_ +* `libsvm <libsvm.html>`_ Low level wrapper for `lib svm <http://www.csie.ntu.edu.tw/~cjlin/libsvm/>`_. Nimble diff --git a/doc/manual/lexing.txt b/doc/manual/lexing.txt index e2f006f04..df6d85636 100644 --- a/doc/manual/lexing.txt +++ b/doc/manual/lexing.txt @@ -289,7 +289,7 @@ Numerical constants are of a single type and have the form:: INT32_LIT = INT_LIT ['\''] ('i' | 'I') '32' INT64_LIT = INT_LIT ['\''] ('i' | 'I') '64' - UINT8_LIT = INT_LIT ['\''] ('u' | 'U') + UINT_LIT = INT_LIT ['\''] ('u' | 'U') UINT8_LIT = INT_LIT ['\''] ('u' | 'U') '8' UINT16_LIT = INT_LIT ['\''] ('u' | 'U') '16' UINT32_LIT = INT_LIT ['\''] ('u' | 'U') '32' diff --git a/doc/manual/stmts.txt b/doc/manual/stmts.txt index 5b1284872..5e47110e9 100644 --- a/doc/manual/stmts.txt +++ b/doc/manual/stmts.txt @@ -2,7 +2,7 @@ Statements and expressions ========================== Nim uses the common statement/expression paradigm: Statements do not -produce a value in contrast to expressions. However, some expressions are +produce a value in contrast to expressions. However, some expressions are statements. Statements are separated into `simple statements`:idx: and @@ -16,9 +16,9 @@ statements always have to be intended. The details can be found in the grammar. Statement list expression ------------------------- -Statements can also occur in an expression context that looks +Statements can also occur in an expression context that looks like ``(stmt1; stmt2; ...; ex)``. This is called -an statement list expression or ``(;)``. The type +an statement list expression or ``(;)``. The type of ``(stmt1; stmt2; ...; ex)`` is the type of ``ex``. All the other statements must be of type ``void``. (One can use ``discard`` to produce a ``void`` type.) ``(;)`` does not introduce a new scope. @@ -30,24 +30,24 @@ Discard statement Example: .. code-block:: nim - proc p(x, y: int): int = + proc p(x, y: int): int = result = x + y discard p(3, 4) # discard the return value of `p` The ``discard`` statement evaluates its expression for side-effects and -throws the expression's resulting value away. +throws the expression's resulting value away. Ignoring the return value of a procedure without using a discard statement is a static error. The return value can be ignored implicitly if the called proc/iterator has -been declared with the `discardable`:idx: pragma: +been declared with the `discardable`:idx: pragma: .. code-block:: nim - proc p(x, y: int): int {.discardable.} = + proc p(x, y: int): int {.discardable.} = result = x + y - + p(3, 4) # now valid An empty ``discard`` statement is often used as a null statement: @@ -98,11 +98,11 @@ T = enum cast[T](0); this may be an invalid value The implicit initialization can be avoided for optimization reasons with the -`noinit`:idx: pragma: +`noinit`:idx: pragma: .. code-block:: nim var - a {.noInit.}: array [0..1023, char] + a {.noInit.}: array [0..1023, char] If a proc is annotated with the ``noinit`` pragma this refers to its implicit ``result`` variable: @@ -113,13 +113,13 @@ If a proc is annotated with the ``noinit`` pragma this refers to its implicit The implicit initialization can be also prevented by the `requiresInit`:idx: type pragma. The compiler requires an explicit initialization then. However -it does a `control flow analysis`:idx: to prove the variable has been +it does a `control flow analysis`:idx: to prove the variable has been initialized and does not rely on syntactic properties: .. code-block:: nim type MyObject = object {.requiresInit.} - + proc p() = # the following is valid: var x: MyObject @@ -129,11 +129,12 @@ initialized and does not rely on syntactic properties: x = a() use x + let statement ------------- A ``let`` statement declares new local and global `single assignment`:idx: -variables and binds a value to them. The syntax is the same as that of the ``var`` +variables and binds a value to them. The syntax is the same as that of the ``var`` statement, except that the keyword ``var`` is replaced by the keyword ``let``. Let variables are not l-values and can thus not be passed to ``var`` parameters nor can their address be taken. They cannot be assigned new values. @@ -141,6 +142,19 @@ nor can their address be taken. They cannot be assigned new values. For let variables the same pragmas are available as for ordinary variables. +Tuple unpacking +--------------- + +In a ``var`` or ``let`` statement tuple unpacking can be performed. The special +identifier ``_`` can be used to ignore some parts of the tuple: + +.. code-block:: nim + proc returnsTuple(): (int, int, int) = (4, 2, 3) + + let (x, _, z) = returnsTuple() + + + Const section ------------- @@ -157,33 +171,33 @@ have no side-effect can be used in constant expressions too: constEval = contains("abc", 'b') # computed at compile time! -The rules for compile-time computability are: +The rules for compile-time computability are: 1. Literals are compile-time computable. 2. Type conversions are compile-time computable. 3. Procedure calls of the form ``p(X)`` are compile-time computable if - ``p`` is a proc without side-effects (see the `noSideEffect pragma`_ - for details) and if ``X`` is a (possibly empty) list of compile-time + ``p`` is a proc without side-effects (see the `noSideEffect pragma`_ + for details) and if ``X`` is a (possibly empty) list of compile-time computable arguments. -Constants cannot be of type ``ptr``, ``ref``, ``var`` or ``object``, nor can +Constants cannot be of type ``ptr``, ``ref``, ``var`` or ``object``, nor can they contain such a type. Static statement/expression --------------------------- -A static statement/expression can be used to enforce compile +A static statement/expression can be used to enforce compile time evaluation explicitly. Enforced compile time evaluation can even evaluate -code that has side effects: +code that has side effects: .. code-block:: static: echo "echo at compile time" -It's a static error if the compiler cannot perform the evaluation at compile +It's a static error if the compiler cannot perform the evaluation at compile time. The current implementation poses some restrictions for compile time @@ -217,7 +231,7 @@ the ``:`` are executed. This goes on until the last ``elif``. If all conditions fail, the ``else`` part is executed. If there is no ``else`` part, execution continues with the statement after the ``if`` statement. -The scoping for an ``if`` statement is slightly subtle to support an important +The scoping for an ``if`` statement is slightly subtle to support an important use case. A new scope starts for the ``if``/``elif`` condition and ends after the corresponding *then* block: @@ -229,7 +243,7 @@ the corresponding *then* block: else: # 'm' not declared here -In the example the scopes have been enclosed in ``{| |}``. +In the example the scopes have been enclosed in ``{| |}``. Case statement @@ -244,7 +258,7 @@ Example: echo("permission denied") of "go-for-a-walk": echo("please yourself") else: echo("unknown command") - + # indentation of the branches is also allowed; and so is an optional colon # after the selecting expression: case readline(stdin): @@ -252,15 +266,15 @@ Example: echo("permission denied") of "go-for-a-walk": echo("please yourself") else: echo("unknown command") - + The ``case`` statement is similar to the if statement, but it represents a multi-branch selection. The expression after the keyword ``case`` is evaluated and if its value is in a *slicelist* the corresponding statements (after the ``of`` keyword) are executed. If the value is not in any given *slicelist* the ``else`` part is executed. If there is no ``else`` -part and not all possible values that ``expr`` can hold occur in a -``slicelist``, a static error occurs. This holds only for expressions of +part and not all possible values that ``expr`` can hold occur in a +``slicelist``, a static error occurs. This holds only for expressions of ordinal types. "All possible values" of ``expr`` are determined by ``expr``'s type. To suppress the static error an ``else`` part with an empty ``discard`` statement should be used. @@ -281,7 +295,7 @@ expanded into a list of its elements: of SymChars, '_': echo "an identifier" of '0'..'9': echo "a number" else: echo "other" - + # is equivalent to: proc classify(s: string) = case s[0] @@ -580,14 +594,14 @@ A table constructor is syntactic sugar for an array constructor: .. code-block:: nim {"key1": "value1", "key2", "key3": "value2"} - + # is the same as: [("key1", "value1"), ("key2", "value2"), ("key3", "value2")] -The empty table can be written ``{:}`` (in contrast to the empty set +The empty table can be written ``{:}`` (in contrast to the empty set which is ``{}``) which is thus another way to write as the empty array -constructor ``[]``. This slightly unusal way of supporting tables +constructor ``[]``. This slightly unusal way of supporting tables has lots of advantages: * The order of the (key,value)-pairs is preserved, thus it is easy to diff --git a/doc/manual/syntax.txt b/doc/manual/syntax.txt index cf44eb588..24644bce2 100644 --- a/doc/manual/syntax.txt +++ b/doc/manual/syntax.txt @@ -15,8 +15,6 @@ Associativity Binary operators whose first character is ``^`` are right-associative, all other binary operators are left-associative. -Operators ending in ``>`` but longer than a single character are -called `arrow like`:idx:. Precedence @@ -33,9 +31,12 @@ as ``(@x).abc`` whereas ``$x.abc`` is parsed as ``$(x.abc)``. For binary operators that are not keywords the precedence is determined by the following rules: +Operators ending in either ``->``, ``~>`` or ``=>`` are called +`arrow like`:idx:, and have the lowest precedence of all operators. + If the operator ends with ``=`` and its first character is none of ``<``, ``>``, ``!``, ``=``, ``~``, ``?``, it is an *assignment operator* which -has the lowest precedence. +has the second lowest precedence. Otherwise precedence is determined by the first character. @@ -43,14 +44,14 @@ Otherwise precedence is determined by the first character. Precedence level Operators First character Terminal symbol ================ =============================================== ================== =============== 10 (highest) ``$ ^`` OP10 - 9 ``* / div mod shl shr %`` ``* % \ /`` OP9 - 8 ``+ -`` ``+ ~ |`` OP8 + 9 ``* / div mod shl shr %`` ``* % \ /`` OP9 + 8 ``+ -`` ``+ - ~ |`` OP8 7 ``&`` ``&`` OP7 6 ``..`` ``.`` OP6 - 5 ``== <= < >= > != in notin is isnot not of`` ``= < > !`` OP5 + 5 ``== <= < >= > != in notin is isnot not of`` ``= < > !`` OP5 4 ``and`` OP4 3 ``or xor`` OP3 - 2 ``@ : ?`` OP2 + 2 ``@ : ?`` OP2 1 *assignment operator* (like ``+=``, ``*=``) OP1 0 (lowest) *arrow like operator* (like ``->``, ``=>``) OP0 ================ =============================================== ================== =============== @@ -67,7 +68,7 @@ is still parsed as ``1 + (3 * 4)``, but ``1+3 * 4`` is parsed as ``(1+3) * 4``: .. code-block:: nim #! strongSpaces - if foo+4 * 4 == 8 and b&c | 9 ++ + if foo+4 * 4 == 8 and b&c | 9 ++ bar: echo "" # is parsed as diff --git a/doc/manual/type_bound_ops.txt b/doc/manual/type_bound_ops.txt index efa5578d4..c707979fe 100644 --- a/doc/manual/type_bound_ops.txt +++ b/doc/manual/type_bound_ops.txt @@ -127,8 +127,8 @@ The signature has to be: .. code-block:: nim proc `=deepCopy`(x: T): T -This mechanism is used by most data structures that support shared memory like -channels to implement thread safe automatic memory management. +This mechanism will be used by most data structures that support shared memory +like channels to implement thread safe automatic memory management. The builtin ``deepCopy`` can even clone closures and their environments. See the documentation of `spawn`_ for details. diff --git a/doc/nimc.txt b/doc/nimc.txt index 831fce567..fb1873539 100644 --- a/doc/nimc.txt +++ b/doc/nimc.txt @@ -386,6 +386,25 @@ Example: As can be seen from the example, to Nim symbols can be referred via backticks. Use two backticks to produce a single verbatim backtick. +For a toplevel emit statement the section where in the generated C/C++ file +the code should be emitted can be influenced via the +prefixes ``/*TYPESECTION*/`` or ``/*VARSECTION*/``: + +.. code-block:: Nim + {.emit: """/*TYPESECTION*/ + struct Vector3 { + public: + Vector3(): x(5) {} + Vector3(float x_): x(x_) {} + float x; + }; + """.} + + type Vector3 {.importcpp: "Vector3", nodecl} = object + x: cfloat + + proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl} + ImportCpp pragma ---------------- @@ -506,7 +525,7 @@ For example: .. code-block:: nim type Input {.importcpp: "System::Input".} = object - proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()".} + proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.} let x: ptr Input = getSubsystem[Input]() @@ -596,6 +615,25 @@ Produces: x[6] = 91.4; +- If more precise control is needed, the apostrophe ``'`` can be used in the + supplied pattern to denote the concrete type parameters of the generic type. + See the usage of the apostrophe operator in proc patterns for more details. + +.. code-block:: nim + + type + VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object + + var x: VectorIterator[cint] + + +Produces: + +.. code-block:: C + + std::vector<int>::iterator x; + + ImportObjC pragma ----------------- Similar to the `importc pragma for C <manual.html#importc-pragma>`_, the diff --git a/doc/nimsuggest.txt b/doc/nimsuggest.txt new file mode 100644 index 000000000..2b52196b9 --- /dev/null +++ b/doc/nimsuggest.txt @@ -0,0 +1,174 @@ +================================ + Nim IDE Integration Guide +================================ + +:Author: Unknown +:Version: |nimversion| + +.. contents:: + + +Nim differs from many other compilers in that it is really fast, +and being so fast makes it suited to provide external queries for +text editors about the source code being written. Through the +``nimsuggest`` tool, any IDE +can query a ``.nim`` source file and obtain useful information like +definition of symbols or suggestions for completion. + +This document will guide you through the available options. If you +want to look at practical examples of nimsuggest support you can look +at the +`various editor integrations <https://github.com/Araq/Nim/wiki/Editor-Support>`_ +already available. + + +Installation +============ + +Nimsuggest is available as a Nimble package but currently does not install +properly via Nimble. As nimsuggest is part of the compiler it also doesn't make +too much sense as a Nimble package. Instead we will do the building manually:: + + cd compiler/nimsuggest + nim c -d:release nimsuggest + cp nimsuggest ../../bin + # OR: copy the nimsuggest binary to where your 'nim' binary is + cd ../.. + + + +Nimsuggest invocation +===================== + +Run it via ``nimsuggest --stdin myproject.nim``. Nimsuggest is a server that +takes queries that are related to ``myproject``. There is some support so that +you can throw random ``.nim`` files which are not part of ``myproject`` at +Nimsuggest too, but usually the query refer to modules/files that are part of +``myproject``. + +``--stdin`` means that Nimsuggest reads the query from ``stdin``. This is great +for testing things out and playing with it but for an editor communication +via sockets is more reasonable so that is the default. It listens to port 6000 +by default. + + +Specifying the location of the query +------------------------------------ + +Nimsuggest than waits for queries to process. A query consists of a +cryptic 3 letter "command" ``def`` or ``con`` or ``sug`` or ``use`` followed by +a location. A query location consists of: + + +``file.nim`` + This is the name of the module or include file the query refers to. + +``dirtyfile.nim`` + This is optional. + + The ``file`` paramater is enough for static analysis, but IDEs + tend to have *unsaved buffers* where the user may still be in + the middle of typing a line. In such situations the IDE can + save the current contents to a temporary file and then use the + ``dirtyfile.nim`` option to tell Nimsuggest that ``foobar.nim`` should + be taken from ``temporary/foobar.nim``. + + +``line`` + An integer with the line you are going to query. For the compiler + lines start at **1**. + +``col`` + An integer with the column you are going to query. For the + compiler columns start at **1**. + + +Definitions +----------- + +The ``def`` Nimsuggest command performs a query about the definition +of a specific symbol. If available, Nimsuggest will answer with the +type, source file, line/column information and other accessory data +if available like a docstring. With this information an IDE can +provide the typical *Jump to definition* where a user puts the +cursor on a symbol or uses the mouse to select it and is redirected +to the place where the symbol is located. + +Since Nim is implemented in Nim, one of the nice things of +this feature is that any user with an IDE supporting it can quickly +jump around the standard library implementation and see exactly +what a proc does, learning about the language and seeing real life +examples of how to write/implement specific features. + +Nimsuggest will always answer with a single definition or none if it +can't find any valid symbol matching the position of the query. + + +Suggestions +----------- + +The ``sug`` Nimsuggest command performs a query about possible +completion symbols at some point in the file. + +The typical usage scenario for this option is to call it after the +user has typed the dot character for `the object oriented call +syntax <tut2.html#method-call-syntax>`_. Nimsuggest will try to return +the suggestions sorted first by scope (from innermost to outermost) +and then by item name. + + +Invocation context +------------------ + +The ``con`` Nimsuggest command is very similar to the suggestions +command, but instead of being used after the user has typed a dot +character, this one is meant to be used after the user has typed +an opening brace to start typing parameters. + + +Symbol usages +------------- + +The ``use`` Nimsuggest command lists all usages of the symbol at +a position. IDEs can use this to find all the places in the file +where the symbol is used and offer the user to rename it in all +places at the same time. + +For this kind of query the IDE will most likely ignore all the +type/signature info provided by Nimsuggest and concentrate on the +filename, line and column position of the multiple returned answers. + + + +Parsing nimsuggest output +========================= + +Nimsuggest output is always returned on single lines separated by +tab characters (``\t``). The values of each column are: + +1. Three characters indicating the type of returned answer (e.g. + ``def`` for definition, ``sug`` for suggestion, etc). +2. Type of the symbol. This can be ``skProc``, ``skLet``, and just + about any of the enums defined in the module ``compiler/ast.nim``. +3. Full qualitifed path of the symbol. If you are querying a symbol + defined in the ``proj.nim`` file, this would have the form + ``proj.symbolName``. +4. Type/signature. For variables and enums this will contain the + type of the symbol, for procs, methods and templates this will + contain the full unique signature (e.g. ``proc (File)``). +5. Full path to the file containing the symbol. +6. Line where the symbol is located in the file. Lines start to + count at **1**. +7. Column where the symbol is located in the file. Columns start + to count at **1**. +8. Docstring for the symbol if available or the empty string. To + differentiate the docstring from end of answer, + the docstring is always provided enclosed in double quotes, and + if the docstring spans multiple lines, all following lines of the + docstring will start with a blank space to align visually with + the starting quote. + + Also, you won't find raw ``\n`` characters breaking the one + answer per line format. Instead you will need to parse sequences + in the form ``\xHH``, where *HH* is a hexadecimal value (e.g. + newlines generate the sequence ``\x0A``). diff --git a/doc/tools.txt b/doc/tools.txt index 7f2830879..b0a45c575 100644 --- a/doc/tools.txt +++ b/doc/tools.txt @@ -4,6 +4,11 @@ Tools available with Nim The standard distribution ships with the following tools: +- | `Nimsuggest for IDE support <nimsuggest.html>`_ + | Through the ``nimsuggest`` tool, any IDE can query a ``.nim`` source file + and obtain useful information like definition of symbols or suggestions for + completion. + - | `Nim Installation Generator <niminst.html>`_ | How to generate a nice installer for your Nim program. diff --git a/doc/tut1.txt b/doc/tut1.txt index cb5a0c8dd..58ace1dbe 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -16,7 +16,7 @@ Introduction </p></blockquote> -This document is a tutorial for the programming language *Nim*. +This document is a tutorial for the programming language *Nim*. This tutorial assumes that you are familiar with basic programming concepts like variables, types or statements but is kept very basic. The `manual <manual.html>`_ contains many more examples of the advanced language features. @@ -50,7 +50,7 @@ Commonly used commands and switches have abbreviations, so you can also use:: nim c -r greetings.nim To compile a release version use:: - + nim c -d:release greetings.nim By default the Nim compiler generates a large amount of runtime checks @@ -116,7 +116,7 @@ hash character ``#``. Documentation comments start with ``##``: .. code-block:: nim # A comment. - + var myVariable: int ## a documentation comment @@ -200,7 +200,7 @@ constant declaration at compile time: .. code-block:: nim const x = "abc" # the constant x contains the string "abc" - + Indentation can be used after the ``const`` keyword to list a whole section of constants: @@ -214,7 +214,7 @@ constants: The let statement ================= -The ``let`` statement works like the ``var`` statement but the declared +The ``let`` statement works like the ``var`` statement but the declared symbols are *single assignment* variables: After the initialization their value cannot change: @@ -228,7 +228,7 @@ and put it into a data section": .. code-block:: const input = readLine(stdin) # Error: constant expression expected - + .. code-block:: let input = readLine(stdin) # works @@ -310,8 +310,8 @@ the compiler that for every other value nothing should be done: else: discard The empty `discard statement`_ is a *do 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 all possible string values: +that a case statement with an else part cannot fail and thus the error +disappears. Note that it is impossible to cover all possible string values: that is why string cases always need an ``else`` branch. In general the case statement is used for subrange types or enumerations where @@ -406,7 +406,7 @@ The block's *label* (``myblock`` in the example) is optional. Break statement --------------- A block can be left prematurely with a ``break`` statement. The break statement -can leave a ``while``, ``for``, or a ``block`` statement. It leaves the +can leave a ``while``, ``for``, or a ``block`` statement. It leaves the innermost construct, unless a label of a block is given: .. code-block:: nim @@ -461,7 +461,7 @@ differences: * The statements within a branch do not open a new scope. * The compiler checks the semantics and produces code *only* for the statements that belong to the first condition that evaluates to ``true``. - + The ``when`` statement is useful for writing platform specific code, similar to the ``#ifdef`` construct in the C programming language. @@ -486,14 +486,14 @@ to be indented, but single simple statements do not: .. code-block:: nim # no indentation needed for single assignment statement: if x: x = false - + # indentation needed for nested if statement: if x: if y: y = false else: y = true - + # indentation needed, because two statements follow the condition: if x: x = false @@ -514,7 +514,7 @@ contain indentation at certain places for better readability: As a rule of thumb, indentation within expressions is allowed after operators, an open parenthesis and after commas. -With parenthesis and semicolons ``(;)`` you can use statements where only +With parenthesis and semicolons ``(;)`` you can use statements where only an expression is allowed: .. code-block:: nim @@ -560,45 +560,45 @@ Some terminology: in the example ``question`` is called a (formal) *parameter*, Result variable --------------- -A procedure that returns a value has an implicit ``result`` variable declared +A procedure that returns a value has an implicit ``result`` variable declared that represents the return value. A ``return`` statement with no expression is a -shorthand for ``return result``. The ``result`` value is always returned +shorthand for ``return result``. The ``result`` value is always returned automatically at the end a procedure if there is no ``return`` statement at the exit. .. code-block:: nim - proc sumTillNegative(x: varargs[int]): int = + proc sumTillNegative(x: varargs[int]): int = for i in x: if i < 0: return - result = result + i - + result = result + i + echo sumTillNegative() # echos 0 echo sumTillNegative(3, 4, 5) # echos 12 echo sumTillNegative(3, 4 , -1 , 6) # echos 7 -The ``result`` variable is already implicitly declared at the start of the +The ``result`` variable is already implicitly declared at the start of the function, so declaring it again with 'var result', for example, would shadow it with a normal variable of the same name. The result variable is also already initialised with the type's default value. Note that referential data types will be ``nil`` at the start of the procedure, and thus may require manual initialisation. - + Parameters ---------- Parameters are constant in the procedure body. By default, their value cannot be -changed because this allows the compiler to implement parameter passing in the +changed because this allows the compiler to implement parameter passing in the most efficient way. If a mutable variable is needed inside the procedure, it has to be declared with ``var`` in the procedure body. Shadowing the parameter name -is possible, and actually an idiom: +is possible, and actually an idiom: .. code-block:: nim proc printSeq(s: seq, nprinted: int = -1) = var nprinted = if nprinted == -1: s.len else: min(nprinted, s.len) for i in 0 .. <nprinted: echo s[i] - + If the procedure needs to modify the argument for the caller, a ``var`` parameter can be used: @@ -630,12 +630,12 @@ allow to silently throw away a return value: The return value can be ignored implicitly if the called proc/iterator has -been declared with the ``discardable`` pragma: +been declared with the ``discardable`` pragma: .. code-block:: nim - proc p(x, y: int): int {.discardable.} = + proc p(x, y: int): int {.discardable.} = return x + y - + p(3, 4) # now valid The ``discard`` statement can also be used to create block comments as @@ -899,7 +899,7 @@ object on the heap, so there is a trade-off to be made here. Integers -------- -Nim has these integer types built-in: +Nim has these integer types built-in: ``int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64``. The default integer type is ``int``. Integer literals can have a *type suffix* @@ -1114,7 +1114,7 @@ Arrays An array is a simple fixed length container. Each element in the array has the same type. The array's index type can be any ordinal type. -Arrays can be constructed via ``[]``: +Arrays can be constructed via ``[]``: .. code-block:: nim @@ -1370,12 +1370,12 @@ integer. var building: tuple[street: string, number: int] building = ("Rue del Percebe", 13) echo(building.street) - + # The following line does not compile, they are different tuples! #person = building # --> Error: type mismatch: got (tuple[street: string, number: int]) # but expected 'Person' - + # The following works because the field names and types are the same. var teacher: tuple[name: string, age: int] = ("Mark", 42) person = teacher @@ -1450,13 +1450,13 @@ operators perform implicit dereferencing operations for reference types: type Node = ref NodeObj - NodeObj = object - le, ri: PNode + NodeObj = object + le, ri: Node data: int var n: Node new(n) - n.data = 9 + n.data = 9 # no need to write n[].data; in fact n[].data is highly discouraged! To allocate a new traced object, the built-in procedure ``new`` has to be used. @@ -1559,9 +1559,9 @@ This is best illustrated by an example: A symbol of a module *can* be *qualified* with the ``module.symbol`` syntax. If -the symbol is ambiguous, it even *has* to be qualified. A symbol is ambiguous -if it is defined in two (or more) different modules and both modules are -imported by a third one: +the symbol is ambiguous, it even *has* to be qualified. A symbol is ambiguous +if it is defined in two (or more) different modules and both modules are +imported by a third one: .. code-block:: nim # Module A |