diff options
Diffstat (limited to 'doc')
-rw-r--r-- | doc/apis.rst (renamed from doc/apis.txt) | 0 | ||||
-rw-r--r-- | doc/backends.rst (renamed from doc/backends.txt) | 0 | ||||
-rw-r--r-- | doc/intern.rst (renamed from doc/intern.txt) | 0 | ||||
-rw-r--r-- | doc/lib.rst | 29 | ||||
-rw-r--r-- | doc/manual.rst | 188 | ||||
-rw-r--r-- | doc/nep1.rst | 76 | ||||
-rw-r--r-- | doc/nimc.rst | 82 | ||||
-rw-r--r-- | doc/tools.rst (renamed from doc/tools.txt) | 11 | ||||
-rw-r--r-- | doc/tut1.rst | 13 |
9 files changed, 293 insertions, 106 deletions
diff --git a/doc/apis.txt b/doc/apis.rst index 277c1925b..277c1925b 100644 --- a/doc/apis.txt +++ b/doc/apis.rst diff --git a/doc/backends.txt b/doc/backends.rst index 13ef7bf4d..13ef7bf4d 100644 --- a/doc/backends.txt +++ b/doc/backends.rst diff --git a/doc/intern.txt b/doc/intern.rst index b253cac42..b253cac42 100644 --- a/doc/intern.txt +++ b/doc/intern.rst diff --git a/doc/lib.rst b/doc/lib.rst index f0569070d..bfb7306fb 100644 --- a/doc/lib.rst +++ b/doc/lib.rst @@ -425,7 +425,7 @@ Miscellaneous Turns access violations or segfaults into a ``NilAccessError`` exception. Modules for JS backend ---------------------------- +---------------------- * `dom <dom.html>`_ Declaration of the Document Object Model for the JS backend. @@ -440,30 +440,6 @@ Modules for JS backend Wrapper of core JavaScript functions. For most purposes you should be using the ``math``, ``json``, and ``times`` stdlib modules instead of this module. -Deprecated modules ------------------- - -* `asyncio <asyncio.html>`_ - This module implements an asynchronous event loop for sockets. - **Deprecated since version 0.11.2:** - Use the `asyncnet <asyncnet.html>`_ together with the - `asyncdispatch <asyncdispatch.html>`_ module instead. - -* `ftpclient <ftpclient.html>`_ - This module implements an FTP client. - **Deprecated since version 0.11.3:** - Use the `asyncftpclient <asyncftpclient.html>`_ module instead. - -* `sockets <sockets.html>`_ - This module implements a simple portable type-safe sockets layer. - **Deprecated since version 0.11.2:** - Use the `net <net.html>`_ or the `rawsockets <rawsockets.html>`_ module - instead. - -* `rawsockets <rawsockets.html>`_ - **Deprecated since version 0.11.4:** - This module has been renamed to `nativesockets <nativesockets.html>`_. - Impure libraries ================ @@ -475,9 +451,6 @@ Regular expressions This module contains procedures and operators for handling regular expressions. The current implementation uses PCRE. -* `nre <nre.html>`_ - Another implementation of procedures for using regular expressions. Also uses - PCRE. Database support diff --git a/doc/manual.rst b/doc/manual.rst index 4f0530a8a..7946e88dd 100644 --- a/doc/manual.rst +++ b/doc/manual.rst @@ -17,8 +17,7 @@ About this document =================== **Note**: This document is a draft! Several of Nim's features may need more -precise wording. This manual is constantly evolving until the 1.0 release and is -not to be considered as the final proper specification. +precise wording. This manual is constantly evolving into a proper specification. This document describes the lexis, the syntax, and the semantics of Nim. @@ -433,7 +432,7 @@ Numerical constants are of a single type and have the form:: UINT64_LIT = INT_LIT ['\''] ('u' | 'U') '64' exponent = ('e' | 'E' ) ['+' | '-'] digit ( ['_'] digit )* - FLOAT_LIT = digit (['_'] digit)* (('.' (['_'] digit)* [exponent]) |exponent) + FLOAT_LIT = digit (['_'] digit)* (('.' digit (['_'] digit)* [exponent]) |exponent) FLOAT32_SUFFIX = ('f' | 'F') ['32'] FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX @@ -504,7 +503,7 @@ following characters:: These keywords are also operators: ``and or not xor shl shr div mod in notin is isnot of``. -`=`:tok:, `:`:tok:, `::`:tok: are not available as general operators; they +`.`:tok: `=`:tok:, `:`:tok:, `::`:tok: are not available as general operators; they are used for other notational purposes. ``*:`` is as a special case treated as the two tokens `*`:tok: and `:`:tok: @@ -618,6 +617,55 @@ The grammar's start symbol is ``module``. +Order of evaluation +=================== + +Order of evaluation is strictly left-to-right, inside-out as it is typical for most others +imperative programming languages: + +.. code-block:: nim + :test: "nim c $1" + + var s = "" + + proc p(arg: int): int = + s.add $arg + result = arg + + discard p(p(1) + p(2)) + + doAssert s == "123" + + +Assignments are not special, the left-hand-side expression is evaluated before the +right-hand side: + +.. code-block:: nim + :test: "nim c $1" + + var v = 0 + proc getI(): int = + result = v + inc v + + var a, b: array[0..2, int] + + proc someCopy(a: var int; b: int) = a = b + + a[getI()] = getI() + + doAssert a == [1, 0, 0] + + v = 0 + someCopy(b[getI()], getI()) + + doAssert b == [1, 0, 0] + + +Rationale: Consistency with overloaded assignment or assignment-like operations, +``a = b`` can be read as ``performSomeCopy(a, b)``. + + Types ===== @@ -888,8 +936,12 @@ Now the following holds:: ord(south) == 2 ord(west) == 3 + # Also allowed: + ord(Direction.west) == 3 + Thus, north < east < south < west. The comparison operators can be used -with enumeration types. +with enumeration types. Instead of ``north`` etc, the enum value can also +be qualified with the enum type that it resides in, ``Direction.north``. For better interfacing to other programming languages, the fields of enum types can be assigned an explicit ordinal value. However, the ordinal values @@ -925,18 +977,25 @@ As can be seen from the example, it is possible to both specify a field's ordinal value and its string value by using a tuple. It is also possible to only specify one of them. -An enum can be marked with the ``pure`` pragma so that it's fields are not -added to the current scope, so they always need to be accessed -via ``MyEnum.value``: +An enum can be marked with the ``pure`` pragma so that it's fields are +added to a special module specific hidden scope that is only queried +as the last attempt. Only non-ambiguous symbols are added to this scope. +But one can always access these via type qualification written +as ``MyEnum.value``: .. code-block:: nim type MyEnum {.pure.} = enum - valueA, valueB, valueC, valueD + valueA, valueB, valueC, valueD, amb - echo valueA # error: Unknown identifier - echo MyEnum.valueA # works + OtherEnum {.pure.} = enum + valueX, valueY, valueZ, amb + + + echo valueA # MyEnum.valueA + echo amb # Error: Unclear whether it's MyEnum.amb or OtherEnum.amb + echo MyEnum.amb # OK. String type @@ -945,6 +1004,11 @@ All string literals are of the type ``string``. A string in Nim is very similar to a sequence of characters. However, strings in Nim are both zero-terminated and have a length field. One can retrieve the length with the builtin ``len`` procedure; the length never counts the terminating zero. + +The terminating zero cannot be accessed unless the string is converted +to the ``cstring`` type first. The terminating zero assures that this +conversion can be done in O(1) and without any allocations. + The assignment operator for strings always copies the string. The ``&`` operator concatenates strings. @@ -2925,6 +2989,10 @@ name ``c`` should default to type ``Context``, ``n`` should default to proc bar(c, n, counter) = ... proc baz(c, n) = ... + proc mixedMode(c, n; x, y: int) = + # 'c' is inferred to be of the type 'Context' + # 'n' is inferred to be of the type 'Node' + # But 'x' and 'y' are of type 'int'. The ``using`` section uses the same indentation based grouping syntax as a ``var`` or ``let`` section. @@ -2932,6 +3000,9 @@ a ``var`` or ``let`` section. Note that ``using`` is not applied for ``template`` since untyped template parameters default to the type ``system.untyped``. +Mixing parameters that should use the ``using`` declaration with parameters +that are explicitly typed is possible and requires a semicolon between them. + If expression ------------- @@ -3045,6 +3116,19 @@ the address of variables, but one can't use it on variables declared through # Error: expression has no address +The unsafeAddr operator +----------------------- + +For easier interoperability with other compiled languages such as C, retrieving +the address of a ``let`` variable, a parameter or a ``for`` loop variable, the +``unsafeAddr`` operation can be used: + +.. code-block:: nim + + let myArray = [1, 2, 3] + foreignProcThatTakesAnAddr(unsafeAddr myArray) + + Procedures ========== @@ -4327,6 +4411,34 @@ be inferred to have the equivalent of the `any` type class and thus they will match anything without discrimination. +Generic inference restrictions +------------------------------ + +The types ``var T`` and ``typedesc[T]`` cannot be inferred in a generic +instantiation. The following is not allowed: + +.. code-block:: nim + :test: "nim c $1" + :status: 1 + + proc g[T](f: proc(x: T); x: T) = + f(x) + + proc c(y: int) = echo y + proc v(y: var int) = + y += 100 + var i: int + + # allowed: infers 'T' to be of type 'int' + g(c, 42) + + # not valid: 'T' is not inferred to be of type 'var int' + g(v, i) + + # also not allowed: explict instantiation via 'var int' + g[var int](v, i) + + Concepts -------- @@ -4573,7 +4685,7 @@ type is an instance of it: .. code-block:: nim :test: "nim c $1" - import future, typetraits + import sugar, typetraits type Functor[A] = concept f @@ -5399,12 +5511,17 @@ type ``system.ForLoopStmt`` can rewrite the entirety of a ``for`` loop: newFor.add x[^2][1] newFor.add body result.add newFor + # now wrap the whole macro in a block to create a new scope + result = quote do: + block: `result` for a, b in enumerate(items([1, 2, 3])): echo a, " ", b - for a2, b2 in enumerate([1, 2, 3, 5]): - echo a2, " ", b2 + # without wrapping the macro in a block, we'd need to choose different + # names for `a` and `b` here to avoid redefinition errors + for a, b in enumerate([1, 2, 3, 5]): + echo a, " ", b Currently for loop macros must be enabled explicitly @@ -5414,12 +5531,11 @@ via ``{.experimental: "forLoopMacros".}``. Case statement macros --------------------- -A macro that needs to be called `match`:idx: can be used to -rewrite ``case`` statements in order to -implement `pattern matching`:idx: for certain types. The following -example implements a simplistic form of pattern matching for tuples, -leveraging the existing equality operator for tuples (as provided in - ``system.==``): +A macro that needs to be called `match`:idx: can be used to rewrite +``case`` statements in order to implement `pattern matching`:idx: for +certain types. The following example implements a simplistic form of +pattern matching for tuples, leveraging the existing equality operator +for tuples (as provided in ``system.==``): .. code-block:: nim :test: "nim c $1" @@ -6553,6 +6669,11 @@ The deprecated pragma is used to mark a symbol as deprecated: proc p() {.deprecated.} var x {.deprecated.}: char +This pragma can also take in an optional warning string to relay to developers. + +.. code-block:: nim + proc thing(x: bool) {.deprecated: "See arguments of otherThing()".} + It can also be used as a statement, in that case it takes a list of *renamings*. .. code-block:: nim @@ -6561,7 +6682,6 @@ It can also be used as a statement, in that case it takes a list of *renamings*. Stream = ref object {.deprecated: [TFile: File, PStream: Stream].} - noSideEffect pragma ------------------- The ``noSideEffect`` pragma is used to mark a proc/iterator to have no side @@ -6998,12 +7118,36 @@ Example: .. code-block:: nim {.experimental: "parallel".} - proc useUsing(bar, foo) = + proc useParallel() = parallel: for i in 0..4: echo "echo in parallel" +As a top level statement, the experimental pragma enables a feature for the +rest of the module it's enabled in. This is problematic for macro and generic +instantiations that cross a module scope. Currently these usages have to be +put into a ``.push/pop`` environment: + +.. code-block:: nim + + # client.nim + proc useParallel*[T](unused: T) = + # use a generic T here to show the problem. + {.push experimental: "parallel".} + parallel: + for i in 0..4: + echo "echo in parallel" + + {.pop.} + + +.. code-block:: nim + + import client + useParallel(1) + + Implementation Specific Pragmas =============================== diff --git a/doc/nep1.rst b/doc/nep1.rst index c4d445681..1ef8c3c24 100644 --- a/doc/nep1.rst +++ b/doc/nep1.rst @@ -60,7 +60,7 @@ Spacing and Whitespace Conventions Naming Conventions -------------------------- +------------------ Note: While the rules outlined below are the *current* naming conventions, these conventions have not always been in place. Previously, the naming @@ -147,6 +147,80 @@ changed in the future. an in-place version should get an ``-In`` suffix (``replaceIn`` for this example). +The stdlib API is designed to be **easy to use** and consistent. Ease of use is +measured by the number of calls to achieve a concrete high level action. The +ultimate goal is that the programmer can *guess* a name. + +The library uses a simple naming scheme that makes use of common abbreviations +to keep the names short but meaningful. + + +------------------- ------------ -------------------------------------- +English word To use Notes +------------------- ------------ -------------------------------------- +initialize initT ``init`` is used to create a + value type ``T`` +new newP ``new`` is used to create a + reference type ``P`` +find find should return the position where + something was found; for a bool result + use ``contains`` +contains contains often short for ``find() >= 0`` +append add use ``add`` instead of ``append`` +compare cmp should return an int with the + ``< 0`` ``== 0`` or ``> 0`` semantics; + for a bool result use ``sameXYZ`` +put put, ``[]=`` consider overloading ``[]=`` for put +get get, ``[]`` consider overloading ``[]`` for get; + consider to not use ``get`` as a + prefix: ``len`` instead of ``getLen`` +length len also used for *number of elements* +size size, len size should refer to a byte size +capacity cap +memory mem implies a low-level operation +items items default iterator over a collection +pairs pairs iterator over (key, value) pairs +delete delete, del del is supposed to be faster than + delete, because it does not keep + the order; delete keeps the order +remove delete, del inconsistent right now +include incl +exclude excl +command cmd +execute exec +environment env +variable var +value value, val val is preferred, inconsistent right + now +executable exe +directory dir +path path path is the string "/usr/bin" (for + example), dir is the content of + "/usr/bin"; inconsistent right now +extension ext +separator sep +column col, column col is preferred, inconsistent right + now +application app +configuration cfg +message msg +argument arg +object obj +parameter param +operator opr +procedure proc +function func +coordinate coord +rectangle rect +point point +symbol sym +literal lit +string str +identifier ident +indentation indent +------------------- ------------ -------------------------------------- + + Coding Conventions ------------------ diff --git a/doc/nimc.rst b/doc/nimc.rst index 0682fac03..4082b5378 100644 --- a/doc/nimc.rst +++ b/doc/nimc.rst @@ -143,6 +143,9 @@ which may be used in conjunction with the `compile time define pragmas<manual.html#implementation-specific-pragmas-compile-time-define-pragmas>`_ to override symbols during build time. +Compile time symbols are completely **case insensitive** and underscores are +ignored too. ``--define:FOO`` and ``--define:foo`` are identical. + Configuration files ------------------- @@ -326,40 +329,41 @@ The standard library supports a growing number of ``useX`` conditional defines affecting how some features are implemented. This section tries to give a complete list. -================== ========================================================= -Define Effect -================== ========================================================= -``release`` Turns off runtime checks and turns on the optimizer. -``useWinAnsi`` Modules like ``os`` and ``osproc`` use the Ansi versions - of the Windows API. The default build uses the Unicode - version. -``useFork`` Makes ``osproc`` use ``fork`` instead of ``posix_spawn``. -``useNimRtl`` Compile and link against ``nimrtl.dll``. -``useMalloc`` Makes Nim use C's `malloc`:idx: instead of Nim's - own memory manager, ableit prefixing each allocation with - its size to support clearing memory on reallocation. - This only works with ``gc:none``. -``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime - systems. See the documentation of the `gc <gc.html>`_ - for further information. -``nodejs`` The JS target is actually ``node.js``. -``ssl`` Enables OpenSSL support for the sockets module. -``memProfiler`` Enables memory profiling for the native GC. -``uClibc`` Use uClibc instead of libc. (Relevant for Unix-like OSes) -``checkAbi`` When using types from C headers, add checks that compare - what's in the Nim file with what's in the C header - (requires a C compiler with _Static_assert support, like - any C11 compiler) -``tempDir`` This symbol takes a string as its value, like - ``--define:tempDir:/some/temp/path`` to override the - temporary directory returned by ``os.getTempDir()``. - The value **should** end with a directory separator - character. (Relevant for the Android platform) -``useShPath`` This symbol takes a string as its value, like - ``--define:useShPath:/opt/sh/bin/sh`` to override the - path for the ``sh`` binary, in cases where it is not - located in the default location ``/bin/sh`` -================== ========================================================= +====================== ========================================================= +Define Effect +====================== ========================================================= +``release`` Turns off runtime checks and turns on the optimizer. +``useWinAnsi`` Modules like ``os`` and ``osproc`` use the Ansi versions + of the Windows API. The default build uses the Unicode + version. +``useFork`` Makes ``osproc`` use ``fork`` instead of ``posix_spawn``. +``useNimRtl`` Compile and link against ``nimrtl.dll``. +``useMalloc`` Makes Nim use C's `malloc`:idx: instead of Nim's + own memory manager, ableit prefixing each allocation with + its size to support clearing memory on reallocation. + This only works with ``gc:none``. +``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime + systems. See the documentation of the `gc <gc.html>`_ + for further information. +``nodejs`` The JS target is actually ``node.js``. +``ssl`` Enables OpenSSL support for the sockets module. +``memProfiler`` Enables memory profiling for the native GC. +``uClibc`` Use uClibc instead of libc. (Relevant for Unix-like OSes) +``checkAbi`` When using types from C headers, add checks that compare + what's in the Nim file with what's in the C header + (requires a C compiler with _Static_assert support, like + any C11 compiler) +``tempDir`` This symbol takes a string as its value, like + ``--define:tempDir:/some/temp/path`` to override the + temporary directory returned by ``os.getTempDir()``. + The value **should** end with a directory separator + character. (Relevant for the Android platform) +``useShPath`` This symbol takes a string as its value, like + ``--define:useShPath:/opt/sh/bin/sh`` to override the + path for the ``sh`` binary, in cases where it is not + located in the default location ``/bin/sh``. +``noSignalHandler`` Disable the crash handler from ``system.nim``. +====================== ========================================================= @@ -529,6 +533,16 @@ See the documentation of Nim's soft realtime `GC <gc.html>`_ for further information. +Signal handling in Nim +====================== + +The Nim programming language has no concept of Posix's signal handling +mechanisms. However, the standard library offers some rudimentary support +for signal handling, in particular, segmentation faults are turned into +fatal errors that produce a stack trace. This can be disabled with the +``-d:noSignalHandler`` switch. + + Debugging with Nim ================== diff --git a/doc/tools.txt b/doc/tools.rst index 070deb806..6757621fb 100644 --- a/doc/tools.txt +++ b/doc/tools.rst @@ -5,7 +5,7 @@ Tools available with Nim The standard distribution ships with the following tools: - | `Documentation generator <docgen.html>`_ - | The builtin document generator ``nim doc2`` generates HTML documentation + | The builtin document generator ``nim doc`` generates HTML documentation from ``.nim`` source files. - | `Nimsuggest for IDE support <nimsuggest.html>`_ @@ -13,17 +13,8 @@ The standard distribution ships with the following tools: 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. - - | `C2nim <c2nim.html>`_ | C to Nim source converter. Translates C header files to Nim. - | `nimgrep <nimgrep.html>`_ | Nim search and replace utility. - -- | `endb <endb.html>`_ - | Nim's slow platform independent embedded debugger. - -- | `estp <estp.html>`_ - | Nim's slow platform independent embedded stack trace profiler. diff --git a/doc/tut1.rst b/doc/tut1.rst index e200cfe8b..a7f1b741a 100644 --- a/doc/tut1.rst +++ b/doc/tut1.rst @@ -1112,21 +1112,12 @@ proc can convert it to its underlying integer value. For better interfacing to other programming languages, the symbols of enum types can be assigned an explicit ordinal value. However, the ordinal values -must be in ascending order. A symbol whose ordinal value is not -explicitly given is assigned the value of the previous symbol + 1. - -An explicit ordered enum can have *holes*: - -.. code-block:: nim - :test: "nim c $1" - type - MyEnum = enum - a = 2, b = 4, c = 89 +must be in ascending order. Ordinal types ------------- -Enumerations without holes, integer types, ``char`` and ``bool`` (and +Enumerations, integer types, ``char`` and ``bool`` (and subranges) are called ordinal types. Ordinal types have quite a few special operations: |