diff options
Diffstat (limited to 'doc')
-rw-r--r-- | doc/backends.txt | 6 | ||||
-rw-r--r-- | doc/basicopt.txt | 2 | ||||
-rw-r--r-- | doc/idetools.txt | 2 | ||||
-rw-r--r-- | doc/lib.txt | 22 | ||||
-rw-r--r-- | doc/manual/exceptions.txt | 62 | ||||
-rw-r--r-- | doc/manual/procs.txt | 7 | ||||
-rw-r--r-- | doc/manual/types.txt | 130 | ||||
-rw-r--r-- | doc/nimc.txt | 52 | ||||
-rw-r--r-- | doc/tut1.txt | 6 | ||||
-rw-r--r-- | doc/tut2.txt | 54 |
10 files changed, 150 insertions, 193 deletions
diff --git a/doc/backends.txt b/doc/backends.txt index eb16217cd..ffe2d5e88 100644 --- a/doc/backends.txt +++ b/doc/backends.txt @@ -456,11 +456,7 @@ can then attach a GC to this thread via .. code-block:: nim - setStackBottom(addr(someLocal)) - initGC() - -At the moment this support is still experimental so you need to expose these -functions yourself or submit patches to request a public API. + system.setupForeignThreadGc() It is **not** safe to disable the garbage collector and enable it after the call from your background thread even if the code you are calling is short diff --git a/doc/basicopt.txt b/doc/basicopt.txt index ffb374f18..e366b2718 100644 --- a/doc/basicopt.txt +++ b/doc/basicopt.txt @@ -37,4 +37,4 @@ Options: --advanced show advanced command line switches -h, --help show this help -Note: Even single letter options require the colon: -p:PATH. +Note, single letter options that take an argument require a colon. E.g. -p:PATH. diff --git a/doc/idetools.txt b/doc/idetools.txt index 5429d0c07..e04f530f4 100644 --- a/doc/idetools.txt +++ b/doc/idetools.txt @@ -145,7 +145,7 @@ The ``--usages`` idetools switch 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. Again, a pure string based search and -replace may catch symbols out of the scope of a funcion/loop. +replace may catch symbols out of the scope of a function/loop. For this kind of query the IDE will most likely ignore all the type/signature info provided by idetools and concentrate on the diff --git a/doc/lib.txt b/doc/lib.txt index aba05c2ba..45d9dfd2a 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -18,7 +18,7 @@ low-level interface to a C library. Read this `document <apis.html>`_ for a quick overview of the API design. -The `bottom <#babel>`_ of this page includes a list of 3rd party packages +The `bottom <#nimble>`_ of this page includes a list of 3rd party packages created by the Nim community. These packages are a useful addition to the modules in the standard library. @@ -154,8 +154,8 @@ Generic Operating System Services * `streams <streams.html>`_ This module provides a stream interface and two implementations thereof: - the `PFileStream` and the `PStringStream` which implement the stream - interface for Nim file objects (`TFile`) and strings. Other modules + the `FileStream` and the `StringStream` which implement the stream + interface for Nim file objects (`File`) and strings. Other modules may provide other implementations for this standard stream interface. * `marshal <marshal.html>`_ @@ -581,12 +581,12 @@ Scientific computing * `libsvm <libsvm.html>`_ Low level wrapper for `lib svm <http://www.csie.ntu.edu.tw/~cjlin/libsvm/>`_. -Babel +Nimble ==================== -Babel is a package manager for the Nim programming language. -For instructions on how to install Babel packages see -`its README <https://github.com/nim-code/babel#readme>`_. +Nimble is a package manager for the Nim programming language. +For instructions on how to install Nimble packages see +`its README <https://github.com/nim-lang/babel#readme>`_. Official packages ----------------- @@ -598,7 +598,7 @@ compiler. .. raw:: html <div id="officialPkgList"><b>If you are reading this you are missing - babelpkglist.js or have javascript disabled in your browser.</b></div> + nimblepkglist.js or have javascript disabled in your browser.</b></div> Unofficial packages ------------------- @@ -610,7 +610,7 @@ Nim programming language. .. raw:: html <div id="unofficialPkgList"><b>If you are reading this you are missing - babelpkglist.js or have javascript disabled in your browser.</b></div> + nimblepkglist.js or have javascript disabled in your browser.</b></div> - <script type="text/javascript" src="babelpkglist.js"></script> - <script type="text/javascript" src="http://build.nim-lang.org/packages?callback=gotPackageList"></script> + <script type="text/javascript" src="nimblepkglist.js"></script> + <script type="text/javascript" src="http://irclogs.nim-lang.org/packages?callback=gotPackageList"></script> diff --git a/doc/manual/exceptions.txt b/doc/manual/exceptions.txt index 7cad1c2b4..e40742e0a 100644 --- a/doc/manual/exceptions.txt +++ b/doc/manual/exceptions.txt @@ -47,36 +47,52 @@ the rest of the procedure - that is not within a ``finally`` clause - is not executed (if an exception occurs). -Standalone except and finally statements ----------------------------------------- +Try expression +-------------- -``except`` and ``finally`` can also be used as a stand-alone statements. -Any statements following them in the current block will be considered to be -in an implicit try block: +Try can also be used as an expression; the type of the ``try`` branch then +needs to fit the types of ``except`` branches, but the type of the ``finally`` +branch always has to be ``void``: + +.. code-block:: nim + let x = try: parseInt("133a") + except: -1 + finally: echo "hi" + + +To prevent confusing code there is a parsing limitation; if the ``try`` +follows a ``(`` it has to be written as a one liner: + +.. code-block:: nim + let x = (try: parseInt("133a") except: -1) + + + +Defer statement +--------------- + +Instead of a ``try finally`` statement a ``defer`` statement can be used. + +Any statements following the ``defer`` in the current block will be considered +to be in an implicit try block: .. code-block:: nim var f = open("numbers.txt") - finally: close(f) - ... + defer: close(f) + f.write "abc" + f.write "def" -The ``except`` statement has a limitation in this form: one can't specify the -type of the exception, one has to catch everything. Also, if one wants to use -both ``finally`` and ``except`` one needs to reverse the usual sequence of the -statements. Example: +Is rewritten to: .. code-block:: nim - proc test() = - raise newException(Exception, "Hey ho") - - proc tester() = - finally: echo "3. Finally block" - except: echo "2. Except block" - echo "1. Pre exception" - test() - echo "4. Post exception" - # --> 1, 2, 3 is printed, 4 is never reached - -Top level standalone ``finally`` or ``except`` statements are not supported + var f = open("numbers.txt") + try: + f.write "abc" + f.write "def" + finally: + close(f) + +Top level ``defer`` statements are not supported since it's unclear what such a statement should refer to. diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 156e96f1b..2ebbe494d 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -200,6 +200,8 @@ executable code. Do notation ----------- +**Note:** The future of the ``do`` notation is uncertain. + As a special more convenient notation, proc expressions involved in procedure calls can use the ``do`` keyword: @@ -224,11 +226,6 @@ More than one ``do`` block can appear in a single call: do: # code to undo it -For compatibility with ``stmt`` templates and macros, the ``do`` keyword can be -omitted if the supplied proc doesn't have any parameters and return value. -The compatibility works in the other direction too as the ``do`` syntax can be -used with macros and templates expecting ``stmt`` blocks. - Nonoverloadable builtins ------------------------ diff --git a/doc/manual/types.txt b/doc/manual/types.txt index b028752e8..94611bbbb 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -40,7 +40,7 @@ These integer types are pre-defined: ``int`` the generic signed integer type; its size is platform dependent and has the - same size as a pointer. This type should be used in general. An integer + same size as a pointer. This type should be used in general. An integer literal that has no type suffix is of this type. intXX @@ -51,7 +51,7 @@ intXX ``uint`` the generic `unsigned integer`:idx: type; its size is platform dependent and - has the same size as a pointer. An integer literal with the type + has the same size as a pointer. An integer literal with the type suffix ``'u`` is of this type. uintXX @@ -59,15 +59,15 @@ uintXX (example: uint16 is a 16 bit wide unsigned integer). The current implementation supports ``uint8``, ``uint16``, ``uint32``, ``uint64``. Literals of these types have the suffix 'uXX. - Unsigned operations all wrap around; they cannot lead to over- or + Unsigned operations all wrap around; they cannot lead to over- or underflow errors. In addition to the usual arithmetic operators for signed and unsigned integers -(``+ - *`` etc.) there are also operators that formally work on *signed* -integers but treat their arguments as *unsigned*: They are mostly provided -for backwards compatibility with older versions of the language that lacked -unsigned integer types. These unsigned operations for signed integers use +(``+ - *`` etc.) there are also operators that formally work on *signed* +integers but treat their arguments as *unsigned*: They are mostly provided +for backwards compatibility with older versions of the language that lacked +unsigned integer types. These unsigned operations for signed integers use the ``%`` suffix as convention: @@ -98,7 +98,7 @@ operation meaning kinds of integer types are used: the smaller type is converted to the larger. A `narrowing type conversion`:idx: converts a larger to a smaller type (for -example ``int32 -> int16``. A `widening type conversion`:idx: converts a +example ``int32 -> int16``. A `widening type conversion`:idx: converts a smaller type to a larger type (for example ``int16 -> int32``). In Nim only widening type conversions are *implicit*: @@ -111,7 +111,7 @@ widening type conversions are *implicit*: However, ``int`` literals are implicitly convertible to a smaller integer type 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. For further details, see `Convertible relation`_. @@ -137,12 +137,12 @@ determined). Assignments from the base type to one of its subrange types A subrange type has the same size as its base type (``int`` in the example). Nim requires `interval arithmetic`:idx: for subrange types over a set -of built-in operators that involve constants: ``x %% 3`` is of -type ``range[0..2]``. The following built-in operators for integers are +of built-in operators that involve constants: ``x %% 3`` is of +type ``range[0..2]``. The following built-in operators for integers are affected by this rule: ``-``, ``+``, ``*``, ``min``, ``max``, ``succ``, ``pred``, ``mod``, ``div``, ``%%``, ``and`` (bitwise ``and``). -Bitwise ``and`` only produces a ``range`` if one of its operands is a +Bitwise ``and`` only produces a ``range`` if one of its operands is a constant *x* so that (x+1) is a number of two. (Bitwise ``and`` is then a ``%%`` operation.) @@ -155,7 +155,7 @@ This means that the following code is accepted: of 9: echo "C" of 10: echo "D" # note: no ``else`` required as (x and 3) + 7 has the type: range[7..10] - + Pre-defined floating point types -------------------------------- @@ -186,17 +186,17 @@ The IEEE standard defines five types of floating-point exceptions: for example 0.0/0.0, sqrt(-1.0), and log(-37.8). * Division by zero: divisor is zero and dividend is a finite nonzero number, for example 1.0/0.0. -* Overflow: operation produces a result that exceeds the range of the exponent, +* Overflow: operation produces a result that exceeds the range of the exponent, for example MAXDOUBLE+0.0000000000001e308. -* Underflow: operation produces a result that is too small to be represented +* Underflow: operation produces a result that is too small to be represented as a normal number, for example, MINDOUBLE * MINDOUBLE. -* Inexact: operation produces a result that cannot be represented with infinite +* Inexact: operation produces a result that cannot be represented with infinite precision, for example, 2.0 / 3.0, log(1.1) and 0.1 in input. -The IEEE exceptions are either ignored at runtime or mapped to the +The IEEE exceptions are either ignored at runtime or mapped to the Nim exceptions: `FloatInvalidOpError`:idx:, `FloatDivByZeroError`:idx:, `FloatOverflowError`:idx:, `FloatUnderflowError`:idx:, -and `FloatInexactError`:idx:. +and `FloatInexactError`:idx:. These exceptions inherit from the `FloatingPointError`:idx: base class. Nim provides the pragmas `NaNChecks`:idx: and `InfChecks`:idx: to control @@ -212,7 +212,7 @@ whether the IEEE exceptions are ignored or trap a Nim exception: In the current implementation ``FloatDivByZeroError`` and ``FloatInexactError`` are never raised. ``FloatOverflowError`` is raised instead of ``FloatDivByZeroError``. -There is also a `floatChecks`:idx: pragma that is a short-cut for the +There is also a `floatChecks`:idx: pragma that is a short-cut for the combination of ``NaNChecks`` and ``InfChecks`` pragmas. ``floatChecks`` are turned off as default. @@ -303,7 +303,7 @@ and ``pred`` are not available for them either. The compiler supports the built-in stringify operator ``$`` for enumerations. -The stringify's result can be controlled by explicitly giving the string +The stringify's result can be controlled by explicitly giving the string values to use: .. code-block:: nim @@ -315,12 +315,12 @@ values to use: valueC = 2, valueD = (3, "abc") -As can be seen from the example, it is possible to both specify a field's +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 +added to the current scope, so they always need to be accessed via ``MyEnum.value``: .. code-block:: nim @@ -328,7 +328,7 @@ via ``MyEnum.value``: type MyEnum {.pure.} = enum valueA, valueB, valueC, valueD - + echo valueA # error: Unknown identifier echo MyEnum.valueA # works @@ -364,22 +364,22 @@ cstring type ------------ The ``cstring`` type represents a pointer to a zero-terminated char array compatible to the type ``char*`` in Ansi C. Its primary purpose lies in easy -interfacing with C. The index operation ``s[i]`` means the i-th *char* of +interfacing with C. The index operation ``s[i]`` means the i-th *char* of ``s``; however no bounds checking for ``cstring`` is performed making the index operation unsafe. -A Nim ``string`` is implicitly convertible +A Nim ``string`` is implicitly convertible to ``cstring`` for convenience. If a Nim string is passed to a C-style variadic proc, it is implicitly converted to ``cstring`` too: .. code-block:: nim - proc printf(formatstr: cstring) {.importc: "printf", varargs, + proc printf(formatstr: cstring) {.importc: "printf", varargs, header: "<stdio.h>".} - + printf("This works %s", "as expected") Even though the conversion is implicit, it is not *safe*: The garbage collector -does not consider a ``cstring`` to be a root and may collect the underlying +does not consider a ``cstring`` to be a root and may collect the underlying memory. However in practice this almost never happens as the GC considers stack roots conservatively. One can use the builtin procs ``GC_ref`` and ``GC_unref`` to keep the string data alive for the rare cases where it does @@ -390,7 +390,7 @@ string from a cstring: .. code-block:: nim var str: string = "Hello!" - var cstr: cstring = s + var cstr: cstring = str var newstr: string = $cstr @@ -410,9 +410,9 @@ integers from 0 to ``len(A)-1``. An array expression may be constructed by the array constructor ``[]``. Sequences are similar to arrays but of dynamic length which may change -during runtime (like strings). Sequences are implemented as growable arrays, +during runtime (like strings). Sequences are implemented as growable arrays, allocating pieces of memory as items are added. A sequence ``S`` is always -indexed by integers from 0 to ``len(S)-1`` and its bounds are checked. +indexed by integers from 0 to ``len(S)-1`` and its bounds are checked. Sequences can be constructed by the array constructor ``[]`` in conjunction with the array to sequence operator ``@``. Another way to allocate space for a sequence is to call the built-in ``newSeq`` procedure. @@ -452,11 +452,11 @@ Open arrays Often fixed size arrays turn out to be too inflexible; procedures should be able to deal with arrays of different sizes. The `openarray`:idx: type -allows this; it can only be used for parameters. Openarrays are always -indexed with an ``int`` starting at position 0. The ``len``, ``low`` -and ``high`` operations are available for open arrays too. Any array with -a compatible base type can be passed to an openarray parameter, the index -type does not matter. In addition to arrays sequences can also be passed +allows this; it can only be used for parameters. Openarrays are always +indexed with an ``int`` starting at position 0. The ``len``, ``low`` +and ``high`` operations are available for open arrays too. Any array with +a compatible base type can be passed to an openarray parameter, the index +type does not matter. In addition to arrays sequences can also be passed to an open array parameter. The openarray type cannot be nested: multidimensional openarrays are not @@ -467,7 +467,7 @@ Varargs ------- A ``varargs`` parameter is an openarray parameter that additionally -allows to pass a variable number of arguments to a procedure. The compiler +allows to pass a variable number of arguments to a procedure. The compiler converts the list of arguments to an array implicitly: .. code-block:: nim @@ -494,7 +494,7 @@ type conversions in this context: # is transformed to: myWriteln(stdout, [$123, $"def", $4.0]) -In this example ``$`` is applied to any argument that is passed to the +In this example ``$`` is applied to any argument that is passed to the parameter ``a``. (Note that ``$`` applied to strings is a nop.) @@ -531,7 +531,7 @@ in future versions of the compiler. person = (creditCard: "Peter", id: 20) The implementation aligns the fields for best access performance. The alignment -is compatible with the way the C compiler does it. +is compatible with the way the C compiler does it. For consistency with ``object`` declarations, tuples in a ``type`` section can also be defined with indentation instead of ``[]``: @@ -571,7 +571,7 @@ Object construction ------------------- Objects can also be created with an `object construction expression`:idx: that -has the syntax ``T(fieldA: valueA, fieldB: valueB, ...)`` where ``T`` is +has the syntax ``T(fieldA: valueA, fieldB: valueB, ...)`` where ``T`` is an ``object`` type or a ``ref object`` type: .. code-block:: nim @@ -617,10 +617,10 @@ An example: # the following statement raises an `EInvalidField` exception, because # n.kind's value does not fit and the ``nkString`` branch is not active: n.strVal = "" - + # invalid: would change the active object branch: n.kind = nkInt - + var x = PNode(kind: nkAdd, leftOp: PNode(kind: nkInt, intVal: 4), rightOp: PNode(kind: nkInt, intVal: 2)) # valid: does not change the active object branch: @@ -660,8 +660,8 @@ untraced references are *unsafe*. However for certain low-level operations Traced references are declared with the **ref** keyword, untraced references are declared with the **ptr** keyword. -An empty subscript ``[]`` notation can be used to derefer a reference, -the ``addr`` procedure returns the address of an item. An address is always +An empty subscript ``[]`` notation can be used to derefer a reference, +the ``addr`` procedure returns the address of an item. An address is always an untraced reference. Thus the usage of ``addr`` is an *unsafe* feature. @@ -680,7 +680,7 @@ dereferencing operations for reference types: var n: PNode new(n) - n.data = 9 + n.data = 9 # no need to write n[].data; in fact n[].data is highly discouraged! In order to simplify structural type checking, recursive tuples are not valid: @@ -751,20 +751,20 @@ details like this when mixing garbage collected data with unmanaged memory. Not nil annotation ------------------ -All types for that ``nil`` is a valid value can be annotated to +All types for that ``nil`` is a valid value can be annotated to exclude ``nil`` as a valid value with the ``not nil`` annotation: .. code-block:: nim type PObject = ref TObj not nil TProc = (proc (x, y: int)) not nil - + proc p(x: PObject) = echo "not nil" - + # compiler catches this: p(nil) - + # and also this: var x: PObject p(x) @@ -851,22 +851,22 @@ Examples: forEach(printItem) # this will NOT compile because calling conventions differ - + .. code-block:: nim type TOnMouseMove = proc (x, y: int) {.closure.} - + proc onMouseMove(mouseX, mouseY: int) = # has default calling convention echo "x: ", mouseX, " y: ", mouseY - + proc setOnMouseMove(mouseMoveEvent: TOnMouseMove) = discard - + # ok, 'onMouseMove' has the default calling convention, which is compatible # to 'closure': setOnMouseMove(onMouseMove) - + A subtle issue with procedural types is that the calling convention of the procedure influences the type compatibility: procedural types are only @@ -932,7 +932,7 @@ of the following conditions hold: 3) The procedure has a calling convention that differs from ``nimcall``. 4) The procedure is anonymous. -The rules' purpose is to prevent the case that extending a non-``procvar`` +The rules' purpose is to prevent the case that extending a non-``procvar`` procedure with default parameters breaks client code. The default calling convention is ``nimcall``, unless it is an inner proc (a @@ -964,7 +964,7 @@ types are a perfect tool to model different currencies: type TDollar = distinct int TEuro = distinct int - + var d: TDollar e: TEuro @@ -989,7 +989,7 @@ number without unit; and the same holds for division: proc `*` (x: int, y: TDollar): TDollar = result = TDollar(x * int(y)) - + proc `div` ... This quickly gets tedious. The implementations are trivial and the compiler @@ -1014,7 +1014,7 @@ currency. This can be solved with templates_. template additive(typ: typedesc): stmt = proc `+` *(x, y: typ): typ {.borrow.} proc `-` *(x, y: typ): typ {.borrow.} - + # unary operators: proc `+` *(x: typ): typ {.borrow.} proc `-` *(x: typ): typ {.borrow.} @@ -1036,7 +1036,7 @@ currency. This can be solved with templates_. additive(typ) multiplicative(typ, base) comparable(typ) - + defineCurrency(TDollar, int) defineCurrency(TEuro, int) @@ -1127,21 +1127,21 @@ modules like `db_sqlite <db_sqlite.html>`_. Void type --------- -The ``void`` type denotes the absense of any type. Parameters of +The ``void`` type denotes the absense of any type. Parameters of type ``void`` are treated as non-existent, ``void`` as a return type means that the procedure does not return a value: .. code-block:: nim proc nothing(x, y: void): void = echo "ha" - + nothing() # writes "ha" to stdout The ``void`` type is particularly useful for generic code: .. code-block:: nim proc callProc[T](p: proc (x: T), x: T) = - when T is void: + when T is void: p() else: p(x) @@ -1151,13 +1151,13 @@ The ``void`` type is particularly useful for generic code: callProc[int](intProc, 12) callProc[void](emptyProc) - + However, a ``void`` type cannot be inferred in generic code: .. code-block:: nim - callProc(emptyProc) + callProc(emptyProc) # Error: type mismatch: got (proc ()) - # but expected one of: + # but expected one of: # callProc(p: proc (T), x: T) The ``void`` type is only valid for parameters and return types; other symbols diff --git a/doc/nimc.txt b/doc/nimc.txt index 92acd3979..a2274febd 100644 --- a/doc/nimc.txt +++ b/doc/nimc.txt @@ -550,58 +550,6 @@ in C/C++). **Note**: This pragma will not exist for the LLVM backend. -Source code style -================= - -Nim allows you to `mix freely case and underscores as identifier separators -<manual.html#identifiers-keywords>`_, so variables named ``MyPrecioussInt`` and -``my_preciouss_int`` are equivalent: - -.. code-block:: Nim - var MyPrecioussInt = 3 - # Following line compiles fine! - echo my_preciouss_int - -Since this can lead to many variants of the same source code (you can use -`nimgrep <nimgrep.html>`_ instead of your typical ``grep`` to ignore style -problems) the compiler provides the command ``pretty`` to help unifying the -style of source code. Running ``nim pretty ugly_test.nim`` with this -example will generate a secondary file named ``ugly_test.pretty.nim`` with the -following content: - -.. code-block:: Nim - var MyPrecioussInt = 3 - # Following line compiles fine! - echo MyPrecioussInt - -During execution the ``pretty`` command will also run on Nim's standard -library, since it doesn't differentiate the standard library as something -special, and hence will warn of many *errors* which are out of your hand to -fix, creating respective ``.pretty.nim`` files all the way. You can ignore -these errors if they don't belong to your source and simply compare your -original version to the new pretty one. In fact, running ``pretty`` on our test -file will show the following:: - - Hint: ugly_test [Processing] - ugly_test.nim(1, 4) Error: name should be: myPrecioussInt - ugly_test.nim(1, 4) Error: name should be: myPrecioussInt - -At the moment ``pretty`` will homogenize the style of symbols but will leave -important changes for you to review. In this case the command is warning that a -variable name should not start with a capital letter, which is usually reserved -to `object types <tut2.html#objects>`_. To learn about the accepted `camel case -style <https://en.wikipedia.org/wiki/Camelcase>`_ read `Coding Guidelines in -the Internals of Nim Compiler <intern.html#coding-guidelines>`_ or `Coding -Guidelines <https://github.com/Araq/Nim/wiki/Coding-Guidelines>`_ and `NEP 1 -: Style Guide for Nim Code -<https://github.com/Araq/Nim/wiki/NEP-1-:-Style-Guide-for-Nim-Code>`_ -from the Nim `GitHub wiki<https://github.com/Araq/Nim/wiki>`_. - -This command is safe to run because it will never attempt to overwrite your -existing sources, but the respective ``.pretty.nim`` files **will** be -overwritten without notice. - - DynlibOverride ============== diff --git a/doc/tut1.txt b/doc/tut1.txt index 9d75b1ea2..5901dd02a 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -139,7 +139,7 @@ Numbers Numerical literals are written as in most other languages. As a special twist, underscores are allowed for better readability: ``1_000_000`` (one million). A number that contains a dot (or 'e' or 'E') is a floating point literal: -``1.0e9`` (one million). Hexadecimal literals are prefixed with ``0x``, +``1.0e9`` (one billion). Hexadecimal literals are prefixed with ``0x``, binary literals with ``0b`` and octal literals with ``0o``. A leading zero alone does not produce an octal. @@ -1070,7 +1070,7 @@ Operation Comment ``dec(x, n)`` decrements `x` by `n`; `n` is an integer ``succ(x)`` returns the successor of `x` ``succ(x, n)`` returns the `n`'th successor of `x` -``prec(x)`` returns the predecessor of `x` +``pred(x)`` returns the predecessor of `x` ``pred(x, n)`` returns the `n`'th predecessor of `x` ----------------- -------------------------------------------------------- @@ -1323,7 +1323,7 @@ define operators which accept TSlice objects to define ranges. a = "Nim is a progamming language" b = "Slices are useless." - echo a[10..15] # --> 'a prog' + echo a[7..12] # --> 'a prog' b[11.. -2] = "useful" echo b # --> 'Slices are useful.' diff --git a/doc/tut2.txt b/doc/tut2.txt index 6e239d681..2ae0f18f6 100644 --- a/doc/tut2.txt +++ b/doc/tut2.txt @@ -35,7 +35,7 @@ Object Oriented Programming =========================== While Nim's support for object oriented programming (OOP) is minimalistic, -powerful OOP technics can be used. OOP is seen as *one* way to design a +powerful OOP techniques can be used. OOP is seen as *one* way to design a program, not *the only* way. Often a procedural approach leads to simpler and more efficient code. In particular, prefering composition over inheritance is often the better design. @@ -56,7 +56,7 @@ Objects have access to their type at runtime. There is an .. code-block:: nim type - TPerson = object of TObject + TPerson = object of RootObj name*: string # the * means that `name` is accessible from other modules age: int # no * means that the field is hidden from other modules @@ -76,10 +76,10 @@ never *equivalent*. New object types can only be defined within a type section. Inheritance is done with the ``object of`` syntax. Multiple inheritance is -currently not supported. If an object type has no suitable ancestor, ``TObject`` -can be used as its ancestor, but this is only a convention. Objects that have -no ancestor are implicitly ``final``. You can use the ``inheritable`` pragma -to introduce new object roots apart from ``system.TObject``. (This is used +currently not supported. If an object type has no suitable ancestor, ``RootObj`` +can be used as its ancestor, but this is only a convention. Objects that have +no ancestor are implicitly ``final``. You can use the ``inheritable`` pragma +to introduce new object roots apart from ``system.RootObj``. (This is used in the GTK wrapper for instance.) @@ -199,7 +199,7 @@ This method call syntax is not restricted to objects, it can be used for any type: .. code-block:: nim - + echo("abc".len) # is the same as echo(len("abc")) echo("abc".toUpper()) echo({'a', 'b', 'c'}.card) @@ -212,7 +212,7 @@ So "pure object oriented" code is easy to write: .. code-block:: nim import strutils - + stdout.writeln("Give a list of numbers (separated by spaces): ") stdout.write(stdin.readLine.split.map(parseInt).max.`$`) stdout.writeln(" is the maximum!") @@ -226,9 +226,9 @@ the same. But setting a value is different; for this a special setter syntax is needed: .. code-block:: nim - + type - TSocket* = object of TObject + TSocket* = object of RootObj FHost: int # cannot be accessed from the outside of the module # the `F` prefix is a convention to avoid clashes since # the accessors are named `host` @@ -236,7 +236,7 @@ is needed: proc `host=`*(s: var TSocket, value: int) {.inline.} = ## setter of hostAddr s.FHost = value - + proc host*(s: TSocket): int {.inline.} = ## getter of hostAddr s.FHost @@ -284,7 +284,7 @@ Procedures always use static dispatch. For dynamic dispatch replace the .. code-block:: nim type - PExpr = ref object of TObject ## abstract base class for an expression + PExpr = ref object of RootObj ## abstract base class for an expression PLiteral = ref object of PExpr x: int PPlusExpr = ref object of PExpr @@ -294,15 +294,15 @@ Procedures always use static dispatch. For dynamic dispatch replace the method eval(e: PExpr): int = # override this base method quit "to override!" - + method eval(e: PLiteral): int = e.x method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b) - + proc newLit(x: int): PLiteral = PLiteral(x: x) proc newPlus(a, b: PExpr): PPlusExpr = PPlusExpr(a: a, b: b) - + echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) - + Note that in the example the constructors ``newLit`` and ``newPlus`` are procs because they should use static binding, but ``eval`` is a method because it requires dynamic binding. @@ -313,19 +313,19 @@ dispatching: .. code-block:: nim type - TThing = object of TObject + TThing = object of RootObj TUnit = object of TThing x: int - + method collide(a, b: TThing) {.inline.} = quit "to override!" - + method collide(a: TThing, b: TUnit) {.inline.} = echo "1" - + method collide(a: TUnit, b: TThing) {.inline.} = echo "2" - + var a, b: TUnit collide(a, b) # output: 2 @@ -526,7 +526,7 @@ containers: yield n.data add(stack, n.ri) # push right subtree onto the stack n = n.le # and follow the left pointer - + var root: PBinaryTree[string] # instantiate a PBinaryTree with ``string`` add(root, newNode("hello")) # instantiates ``newNode`` and ``add`` @@ -578,7 +578,7 @@ simple proc for logging: proc log(msg: string) {.inline.} = if debug: stdout.writeln(msg) - + var x = 4 log("x has the value: " & $x) @@ -595,7 +595,7 @@ Turning the ``log`` proc into a template solves this problem: template log(msg: string) = if debug: stdout.writeln(msg) - + var x = 4 log("x has the value: " & $x) @@ -622,11 +622,11 @@ via a special ``:`` syntax: close(f) else: quit("cannot open: " & fn) - + withFile(txt, "ttempl3.txt", fmWrite): txt.writeln("line 1") txt.writeln("line 2") - + In the example the two ``writeln`` statements are bound to the ``body`` parameter. The ``withFile`` template contains boilerplate code and helps to avoid a common bug: to forget to close the file. Note how the @@ -739,7 +739,7 @@ Term rewriting macros --------------------- Term rewriting macros can be used to enhance the compilation process -with user defined optimizations; see this `document <trmacros.html>`_ for +with user defined optimizations; see this `document <trmacros.html>`_ for further information. |