tut2.rst 22 KB

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