tut2.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. ======================
  2. Nim Tutorial (Part II)
  3. ======================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. contents::
  7. Introduction
  8. ============
  9. "Repetition renders the ridiculous reasonable." -- Norman Wildberger
  10. This document is a tutorial for the advanced constructs of the *Nim*
  11. programming language. **Note that this document is somewhat obsolete as the**
  12. `manual <manual.html>`_ **contains many more examples of the advanced language
  13. features.**
  14. Pragmas
  15. =======
  16. Pragmas are Nim's method to give the compiler additional information/
  17. commands without introducing a massive number of new keywords. Pragmas are
  18. enclosed in the special ``{.`` and ``.}`` curly dot brackets. This tutorial
  19. does not cover pragmas. See the `manual <manual.html#pragmas>`_ or `user guide
  20. <nimc.html#additional-features>`_ for a description of the available
  21. pragmas.
  22. Object Oriented Programming
  23. ===========================
  24. While Nim's support for object oriented programming (OOP) is minimalistic,
  25. powerful OOP techniques can be used. OOP is seen as *one* way to design a
  26. program, not *the only* way. Often a procedural approach leads to simpler
  27. and more efficient code. In particular, preferring composition over inheritance
  28. is often the better design.
  29. Inheritance
  30. -----------
  31. Inheritance in Nim is entirely optional. To enable inheritance with
  32. runtime type information the object needs to inherit from
  33. ``RootObj``. This can be done directly, or indirectly by
  34. inheriting from an object that inherits from ``RootObj``. Usually
  35. types with inheritance are also marked as ``ref`` types even though
  36. this isn't strictly enforced. To check at runtime if an object is of a certain
  37. type, the ``of`` operator can be used.
  38. .. code-block:: nim
  39. :test: "nim c $1"
  40. type
  41. Person = ref object of RootObj
  42. name*: string # the * means that `name` is accessible from other modules
  43. age: int # no * means that the field is hidden from other modules
  44. Student = ref object of Person # Student inherits from Person
  45. id: int # with an id field
  46. var
  47. student: Student
  48. person: Person
  49. assert(student of Student) # is true
  50. # object construction:
  51. student = Student(name: "Anton", age: 5, id: 2)
  52. echo student[]
  53. Inheritance is done with the ``object of`` syntax. Multiple inheritance is
  54. currently not supported. If an object type has no suitable ancestor, ``RootObj``
  55. can be used as its ancestor, but this is only a convention. Objects that have
  56. no ancestor are implicitly ``final``. You can use the ``inheritable`` pragma
  57. to introduce new object roots apart from ``system.RootObj``. (This is used
  58. in the GTK wrapper for instance.)
  59. Ref objects should be used whenever inheritance is used. It isn't strictly
  60. necessary, but with non-ref objects assignments such as ``let person: Person =
  61. Student(id: 123)`` will truncate subclass fields.
  62. **Note**: Composition (*has-a* relation) is often preferable to inheritance
  63. (*is-a* relation) for simple code reuse. Since objects are value types in
  64. Nim, composition is as efficient as inheritance.
  65. Mutually recursive types
  66. ------------------------
  67. Objects, tuples and references can model quite complex data structures which
  68. depend on each other; they are *mutually recursive*. In Nim
  69. these types can only be declared within a single type section. (Anything else
  70. would require arbitrary symbol lookahead which slows down compilation.)
  71. Example:
  72. .. code-block:: nim
  73. :test: "nim c $1"
  74. type
  75. Node = ref object # a reference to an object with the following field:
  76. le, ri: Node # left and right subtrees
  77. sym: ref Sym # leaves contain a reference to a Sym
  78. Sym = object # a symbol
  79. name: string # the symbol's name
  80. line: int # the line the symbol was declared in
  81. code: Node # the symbol's abstract syntax tree
  82. Type conversions
  83. ----------------
  84. Nim distinguishes between `type casts`:idx: and `type conversions`:idx:.
  85. Casts are done with the ``cast`` operator and force the compiler to
  86. interpret a bit pattern to be of another type.
  87. Type conversions are a much more polite way to convert a type into another:
  88. They preserve the abstract *value*, not necessarily the *bit-pattern*. If a
  89. type conversion is not possible, the compiler complains or an exception is
  90. raised.
  91. The syntax for type conversions is ``destination_type(expression_to_convert)``
  92. (like an ordinary call):
  93. .. code-block:: nim
  94. proc getID(x: Person): int =
  95. Student(x).id
  96. The ``InvalidObjectConversionError`` exception is raised if ``x`` is not a
  97. ``Student``.
  98. Object variants
  99. ---------------
  100. Often an object hierarchy is overkill in certain situations where simple
  101. variant types are needed.
  102. An example:
  103. .. code-block:: nim
  104. :test: "nim c $1"
  105. # This is an example how an abstract syntax tree could be modelled in Nim
  106. type
  107. NodeKind = enum # the different node types
  108. nkInt, # a leaf with an integer value
  109. nkFloat, # a leaf with a float value
  110. nkString, # a leaf with a string value
  111. nkAdd, # an addition
  112. nkSub, # a subtraction
  113. nkIf # an if statement
  114. Node = ref object
  115. case kind: NodeKind # the ``kind`` field is the discriminator
  116. of nkInt: intVal: int
  117. of nkFloat: floatVal: float
  118. of nkString: strVal: string
  119. of nkAdd, nkSub:
  120. leftOp, rightOp: Node
  121. of nkIf:
  122. condition, thenPart, elsePart: Node
  123. var n = Node(kind: nkFloat, floatVal: 1.0)
  124. # the following statement raises an `FieldError` exception, because
  125. # n.kind's value does not fit:
  126. n.strVal = ""
  127. As can been seen from the example, an advantage to an object hierarchy is that
  128. no conversion between different object types is needed. Yet, access to invalid
  129. object fields raises an exception.
  130. Method call syntax
  131. ------------------
  132. There is a syntactic sugar for calling routines:
  133. The syntax ``obj.method(args)`` can be used instead of ``method(obj, args)``.
  134. If there are no remaining arguments, the parentheses can be omitted:
  135. ``obj.len`` (instead of ``len(obj)``).
  136. This method call syntax is not restricted to objects, it can be used
  137. for any type:
  138. .. code-block:: nim
  139. :test: "nim c $1"
  140. import strutils
  141. echo "abc".len # is the same as echo len("abc")
  142. echo "abc".toUpperAscii()
  143. echo({'a', 'b', 'c'}.card)
  144. stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo")
  145. (Another way to look at the method call syntax is that it provides the missing
  146. postfix notation.)
  147. So "pure object oriented" code is easy to write:
  148. .. code-block:: nim
  149. :test: "nim c $1"
  150. import strutils, sequtils
  151. stdout.writeLine("Give a list of numbers (separated by spaces): ")
  152. stdout.write(stdin.readLine.splitWhitespace.map(parseInt).max.`$`)
  153. stdout.writeLine(" is the maximum!")
  154. Properties
  155. ----------
  156. As the above example shows, Nim has no need for *get-properties*:
  157. Ordinary get-procedures that are called with the *method call syntax* achieve
  158. the same. But setting a value is different; for this a special setter syntax
  159. is needed:
  160. .. code-block:: nim
  161. :test: "nim c $1"
  162. type
  163. Socket* = ref object of RootObj
  164. h: int # cannot be accessed from the outside of the module due to missing star
  165. proc `host=`*(s: var Socket, value: int) {.inline.} =
  166. ## setter of host address
  167. s.h = value
  168. proc host*(s: Socket): int {.inline.} =
  169. ## getter of host address
  170. s.h
  171. var s: Socket
  172. new s
  173. s.host = 34 # same as `host=`(s, 34)
  174. (The example also shows ``inline`` procedures.)
  175. The ``[]`` array access operator can be overloaded to provide
  176. `array properties`:idx:\ :
  177. .. code-block:: nim
  178. :test: "nim c $1"
  179. type
  180. Vector* = object
  181. x, y, z: float
  182. proc `[]=`* (v: var Vector, i: int, value: float) =
  183. # setter
  184. case i
  185. of 0: v.x = value
  186. of 1: v.y = value
  187. of 2: v.z = value
  188. else: assert(false)
  189. proc `[]`* (v: Vector, i: int): float =
  190. # getter
  191. case i
  192. of 0: result = v.x
  193. of 1: result = v.y
  194. of 2: result = v.z
  195. else: assert(false)
  196. The example is silly, since a vector is better modelled by a tuple which
  197. already provides ``v[]`` access.
  198. Dynamic dispatch
  199. ----------------
  200. Procedures always use static dispatch. For dynamic dispatch replace the
  201. ``proc`` keyword by ``method``:
  202. .. code-block:: nim
  203. :test: "nim c $1"
  204. type
  205. Expression = ref object of RootObj ## abstract base class for an expression
  206. Literal = ref object of Expression
  207. x: int
  208. PlusExpr = ref object of Expression
  209. a, b: Expression
  210. # watch out: 'eval' relies on dynamic binding
  211. method eval(e: Expression): int {.base.} =
  212. # override this base method
  213. quit "to override!"
  214. method eval(e: Literal): int = e.x
  215. method eval(e: PlusExpr): int = eval(e.a) + eval(e.b)
  216. proc newLit(x: int): Literal = Literal(x: x)
  217. proc newPlus(a, b: Expression): PlusExpr = PlusExpr(a: a, b: b)
  218. echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
  219. Note that in the example the constructors ``newLit`` and ``newPlus`` are procs
  220. because it makes more sense for them to use static binding, but ``eval`` is a
  221. method because it requires dynamic binding.
  222. **Note:** Starting from Nim 0.20, to use multi-methods one must explicitly pass
  223. ``--multimethods:on`` when compiling.
  224. In a multi-method all parameters that have an object type are used for the
  225. dispatching:
  226. .. code-block:: nim
  227. :test: "nim c --multiMethods:on $1"
  228. type
  229. Thing = ref object of RootObj
  230. Unit = ref object of Thing
  231. x: int
  232. method collide(a, b: Thing) {.inline.} =
  233. quit "to override!"
  234. method collide(a: Thing, b: Unit) {.inline.} =
  235. echo "1"
  236. method collide(a: Unit, b: Thing) {.inline.} =
  237. echo "2"
  238. var a, b: Unit
  239. new a
  240. new b
  241. collide(a, b) # output: 2
  242. As the example demonstrates, invocation of a multi-method cannot be ambiguous:
  243. Collide 2 is preferred over collide 1 because the resolution works from left to
  244. right. Thus ``Unit, Thing`` is preferred over ``Thing, Unit``.
  245. **Performance note**: Nim does not produce a virtual method table, but
  246. generates dispatch trees. This avoids the expensive indirect branch for method
  247. calls and enables inlining. However, other optimizations like compile time
  248. evaluation or dead code elimination do not work with methods.
  249. Exceptions
  250. ==========
  251. In Nim exceptions are objects. By convention, exception types are
  252. suffixed with 'Error'. The `system <system.html>`_ module defines an
  253. exception hierarchy that you might want to stick to. Exceptions derive from
  254. ``system.Exception``, which provides the common interface.
  255. Exceptions have to be allocated on the heap because their lifetime is unknown.
  256. The compiler will prevent you from raising an exception created on the stack.
  257. All raised exceptions should at least specify the reason for being raised in
  258. the ``msg`` field.
  259. A convention is that exceptions should be raised in *exceptional* cases:
  260. For example, if a file cannot be opened, this should not raise an
  261. exception since this is quite common (the file may not exist).
  262. Raise statement
  263. ---------------
  264. Raising an exception is done with the ``raise`` statement:
  265. .. code-block:: nim
  266. :test: "nim c $1"
  267. var
  268. e: ref OSError
  269. new(e)
  270. e.msg = "the request to the OS failed"
  271. raise e
  272. If the ``raise`` keyword is not followed by an expression, the last exception
  273. is *re-raised*. For the purpose of avoiding repeating this common code pattern,
  274. the template ``newException`` in the ``system`` module can be used:
  275. .. code-block:: nim
  276. raise newException(OSError, "the request to the OS failed")
  277. Try statement
  278. -------------
  279. The ``try`` statement handles exceptions:
  280. .. code-block:: nim
  281. :test: "nim c $1"
  282. from strutils import parseInt
  283. # read the first two lines of a text file that should contain numbers
  284. # and tries to add them
  285. var
  286. f: File
  287. if open(f, "numbers.txt"):
  288. try:
  289. let a = readLine(f)
  290. let b = readLine(f)
  291. echo "sum: ", parseInt(a) + parseInt(b)
  292. except OverflowError:
  293. echo "overflow!"
  294. except ValueError:
  295. echo "could not convert string to integer"
  296. except IOError:
  297. echo "IO error!"
  298. except:
  299. echo "Unknown exception!"
  300. # reraise the unknown exception:
  301. raise
  302. finally:
  303. close(f)
  304. The statements after the ``try`` are executed unless an exception is
  305. raised. Then the appropriate ``except`` part is executed.
  306. The empty ``except`` part is executed if there is an exception that is
  307. not explicitly listed. It is similar to an ``else`` part in ``if``
  308. statements.
  309. If there is a ``finally`` part, it is always executed after the
  310. exception handlers.
  311. The exception is *consumed* in an ``except`` part. If an exception is not
  312. handled, it is propagated through the call stack. This means that often
  313. the rest of the procedure - that is not within a ``finally`` clause -
  314. is not executed (if an exception occurs).
  315. If you need to *access* the actual exception object or message inside an
  316. ``except`` branch you can use the `getCurrentException()
  317. <system.html#getCurrentException>`_ and `getCurrentExceptionMsg()
  318. <system.html#getCurrentExceptionMsg>`_ procs from the `system <system.html>`_
  319. module. Example:
  320. .. code-block:: nim
  321. try:
  322. doSomethingHere()
  323. except:
  324. let
  325. e = getCurrentException()
  326. msg = getCurrentExceptionMsg()
  327. echo "Got exception ", repr(e), " with message ", msg
  328. Annotating procs with raised exceptions
  329. ---------------------------------------
  330. Through the use of the optional ``{.raises.}`` pragma you can specify that a
  331. proc is meant to raise a specific set of exceptions, or none at all. If the
  332. ``{.raises.}`` pragma is used, the compiler will verify that this is true. For
  333. instance, if you specify that a proc raises ``IOError``, and at some point it
  334. (or one of the procs it calls) starts raising a new exception the compiler will
  335. prevent that proc from compiling. Usage example:
  336. .. code-block:: nim
  337. proc complexProc() {.raises: [IOError, ArithmeticError].} =
  338. ...
  339. proc simpleProc() {.raises: [].} =
  340. ...
  341. Once you have code like this in place, if the list of raised exception changes
  342. the compiler will stop with an error specifying the line of the proc which
  343. stopped validating the pragma and the raised exception not being caught, along
  344. with the file and line where the uncaught exception is being raised, which may
  345. help you locate the offending code which has changed.
  346. If you want to add the ``{.raises.}`` pragma to existing code, the compiler can
  347. also help you. You can add the ``{.effects.}`` pragma statement to your proc and
  348. the compiler will output all inferred effects up to that point (exception
  349. tracking is part of Nim's effect system). Another more roundabout way to
  350. find out the list of exceptions raised by a proc is to use the Nim ``doc2``
  351. command which generates documentation for a whole module and decorates all
  352. procs with the list of raised exceptions. You can read more about Nim's
  353. `effect system and related pragmas in the manual <manual.html#effect-system>`_.
  354. Generics
  355. ========
  356. Generics are Nim's means to parametrize procs, iterators or types
  357. with `type parameters`:idx:. They are most useful for efficient type safe
  358. containers:
  359. .. code-block:: nim
  360. :test: "nim c $1"
  361. type
  362. BinaryTree*[T] = ref object # BinaryTree is a generic type with
  363. # generic param ``T``
  364. le, ri: BinaryTree[T] # left and right subtrees; may be nil
  365. data: T # the data stored in a node
  366. proc newNode*[T](data: T): BinaryTree[T] =
  367. # constructor for a node
  368. new(result)
  369. result.data = data
  370. proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) =
  371. # insert a node into the tree
  372. if root == nil:
  373. root = n
  374. else:
  375. var it = root
  376. while it != nil:
  377. # compare the data items; uses the generic ``cmp`` proc
  378. # that works for any type that has a ``==`` and ``<`` operator
  379. var c = cmp(it.data, n.data)
  380. if c < 0:
  381. if it.le == nil:
  382. it.le = n
  383. return
  384. it = it.le
  385. else:
  386. if it.ri == nil:
  387. it.ri = n
  388. return
  389. it = it.ri
  390. proc add*[T](root: var BinaryTree[T], data: T) =
  391. # convenience proc:
  392. add(root, newNode(data))
  393. iterator preorder*[T](root: BinaryTree[T]): T =
  394. # Preorder traversal of a binary tree.
  395. # Since recursive iterators are not yet implemented,
  396. # this uses an explicit stack (which is more efficient anyway):
  397. var stack: seq[BinaryTree[T]] = @[root]
  398. while stack.len > 0:
  399. var n = stack.pop()
  400. while n != nil:
  401. yield n.data
  402. add(stack, n.ri) # push right subtree onto the stack
  403. n = n.le # and follow the left pointer
  404. var
  405. root: BinaryTree[string] # instantiate a BinaryTree with ``string``
  406. add(root, newNode("hello")) # instantiates ``newNode`` and ``add``
  407. add(root, "world") # instantiates the second ``add`` proc
  408. for str in preorder(root):
  409. stdout.writeLine(str)
  410. The example shows a generic binary tree. Depending on context, the brackets are
  411. used either to introduce type parameters or to instantiate a generic proc,
  412. iterator or type. As the example shows, generics work with overloading: the
  413. best match of ``add`` is used. The built-in ``add`` procedure for sequences
  414. is not hidden and is used in the ``preorder`` iterator.
  415. Templates
  416. =========
  417. Templates are a simple substitution mechanism that operates on Nim's
  418. abstract syntax trees. Templates are processed in the semantic pass of the
  419. compiler. They integrate well with the rest of the language and share none
  420. of C's preprocessor macros flaws.
  421. To *invoke* a template, call it like a procedure.
  422. Example:
  423. .. code-block:: nim
  424. template `!=` (a, b: untyped): untyped =
  425. # this definition exists in the System module
  426. not (a == b)
  427. assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))
  428. The ``!=``, ``>``, ``>=``, ``in``, ``notin``, ``isnot`` operators are in fact
  429. templates: this has the benefit that if you overload the ``==`` operator,
  430. the ``!=`` operator is available automatically and does the right thing. (Except
  431. for IEEE floating point numbers - NaN breaks basic boolean logic.)
  432. ``a > b`` is transformed into ``b < a``.
  433. ``a in b`` is transformed into ``contains(b, a)``.
  434. ``notin`` and ``isnot`` have the obvious meanings.
  435. Templates are especially useful for lazy evaluation purposes. Consider a
  436. simple proc for logging:
  437. .. code-block:: nim
  438. :test: "nim c $1"
  439. const
  440. debug = true
  441. proc log(msg: string) {.inline.} =
  442. if debug: stdout.writeLine(msg)
  443. var
  444. x = 4
  445. log("x has the value: " & $x)
  446. This code has a shortcoming: if ``debug`` is set to false someday, the quite
  447. expensive ``$`` and ``&`` operations are still performed! (The argument
  448. evaluation for procedures is *eager*).
  449. Turning the ``log`` proc into a template solves this problem:
  450. .. code-block:: nim
  451. :test: "nim c $1"
  452. const
  453. debug = true
  454. template log(msg: string) =
  455. if debug: stdout.writeLine(msg)
  456. var
  457. x = 4
  458. log("x has the value: " & $x)
  459. The parameters' types can be ordinary types or the meta types ``untyped``,
  460. ``typed``, or ``type``. ``type`` suggests that only a type symbol may be given
  461. as an argument, and ``untyped`` means symbol lookups and type resolution is not
  462. performed before the expression is passed to the template.
  463. If the template has no explicit return type,
  464. ``void`` is used for consistency with procs and methods.
  465. To pass a block of statements to a template, use ``untyped`` for the last parameter:
  466. .. code-block:: nim
  467. :test: "nim c $1"
  468. template withFile(f: untyped, filename: string, mode: FileMode,
  469. body: untyped) =
  470. let fn = filename
  471. var f: File
  472. if open(f, fn, mode):
  473. try:
  474. body
  475. finally:
  476. close(f)
  477. else:
  478. quit("cannot open: " & fn)
  479. withFile(txt, "ttempl3.txt", fmWrite):
  480. txt.writeLine("line 1")
  481. txt.writeLine("line 2")
  482. In the example the two ``writeLine`` statements are bound to the ``body``
  483. parameter. The ``withFile`` template contains boilerplate code and helps to
  484. avoid a common bug: to forget to close the file. Note how the
  485. ``let fn = filename`` statement ensures that ``filename`` is evaluated only
  486. once.
  487. Example: Lifting Procs
  488. ----------------------
  489. .. code-block:: nim
  490. :test: "nim c $1"
  491. import math
  492. template liftScalarProc(fname) =
  493. ## Lift a proc taking one scalar parameter and returning a
  494. ## scalar value (eg ``proc sssss[T](x: T): float``),
  495. ## to provide templated procs that can handle a single
  496. ## parameter of seq[T] or nested seq[seq[]] or the same type
  497. ##
  498. ## .. code-block:: Nim
  499. ## liftScalarProc(abs)
  500. ## # now abs(@[@[1,-2], @[-2,-3]]) == @[@[1,2], @[2,3]]
  501. proc fname[T](x: openarray[T]): auto =
  502. var temp: T
  503. type outType = type(fname(temp))
  504. result = newSeq[outType](x.len)
  505. for i in 0..<x.len:
  506. result[i] = fname(x[i])
  507. liftScalarProc(sqrt) # make sqrt() work for sequences
  508. echo sqrt(@[4.0, 16.0, 25.0, 36.0]) # => @[2.0, 4.0, 5.0, 6.0]
  509. Compilation to JavaScript
  510. =========================
  511. Nim code can be compiled to JavaScript. However in order to write
  512. JavaScript-compatible code you should remember the following:
  513. - ``addr`` and ``ptr`` have slightly different semantic meaning in JavaScript.
  514. It is recommended to avoid those if you're not sure how they are translated
  515. to JavaScript.
  516. - ``cast[T](x)`` in JavaScript is translated to ``(x)``, except for casting
  517. between signed/unsigned ints, in which case it behaves as static cast in
  518. C language.
  519. - ``cstring`` in JavaScript means JavaScript string. It is a good practice to
  520. use ``cstring`` only when it is semantically appropriate. E.g. don't use
  521. ``cstring`` as a binary data buffer.
  522. Part 3
  523. ======
  524. Next part will be entirely about metaprogramming via macros: `Part III <tut3.html>`_