tut2.rst 22 KB

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