summary refs log tree commit diff stats
path: root/lib/pure/unittest.nim
blob: bb4e2867c4011274d804b5dfec27d21ab087b09c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#
#
#            Nim's Runtime Library
#        (c) Copyright 2015 Nim Contributors
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## :Author: Zahary Karadjov
##
## **Note**: Instead of ``unittest.nim``, please consider to use
## the ``testament`` tool which offers process isolation for your tests.
## Also ``when isMainModule: doAssert conditionHere`` is usually a
## much simpler solution for testing purposes.
##
## This module implements boilerplate to make unit testing easy.
##
## The test status and name is printed after any output or traceback.
##
## Tests can be nested, however failure of a nested test will not mark the
## parent test as failed. Setup and teardown are inherited. Setup can be
## overridden locally.
##
## Compiled test files return the number of failed test as exit code, while
## ``nim c -r <testfile.nim>`` exits with 0 or 1
##
## Running a single test
## =====================
##
## Specify the test name as a command line argument.
##
## .. code::
##
##   nim c -r test "my test name" "another test"
##
## Multiple arguments can be used.
##
## Running a single test suite
## ===========================
##
## Specify the suite name delimited by ``"::"``.
##
## .. code::
##
##   nim c -r test "my test name::"
##
## Selecting tests by pattern
## ==========================
##
## A single ``"*"`` can be used for globbing.
##
## Delimit the end of a suite name with ``"::"``.
##
## Tests matching **any** of the arguments are executed.
##
## .. code::
##
##   nim c -r test fast_suite::mytest1 fast_suite::mytest2
##   nim c -r test "fast_suite::mytest*"
##   nim c -r test "auth*::" "crypto::hashing*"
##   # Run suites starting with 'bug #' and standalone tests starting with '#'
##   nim c -r test 'bug #*::' '::#*'
##
## Examples
## ========
##
## .. code:: nim
##
##   suite "description for this stuff":
##     echo "suite setup: run once before the tests"
##
##     setup:
##       echo "run before each test"
##
##     teardown:
##       echo "run after each test"
##
##     test "essential truths":
##       # give up and stop if this fails
##       require(true)
##
##     test "slightly less obvious stuff":
##       # print a nasty message and move on, skipping
##       # the remainder of this block
##       check(1 != 1)
##       check("asd"[2] == 'd')
##
##     test "out of bounds error is thrown on bad access":
##       let v = @[1, 2, 3]  # you can do initialization here
##       expect(IndexDefect):
##         discard v[4]
##
##     echo "suite teardown: run once after the tests"

import std/private/since

import
  macros, strutils, streams, times, sets, sequtils

when declared(stdout):
  import os

const useTerminal = not defined(js)

when useTerminal:
  import terminal

type
  TestStatus* = enum ## The status of a test when it is done.
    OK,
    FAILED,
    SKIPPED

  OutputLevel* = enum ## The output verbosity of the tests.
    PRINT_ALL,        ## Print as much as possible.
    PRINT_FAILURES,   ## Print only the failed tests.
    PRINT_NONE        ## Print nothing.

  TestResult* = object
    suiteName*: string
      ## Name of the test suite that contains this test case.
      ## Can be ``nil`` if the test case is not in a suite.
    testName*: string
      ## Name of the test case
    status*: TestStatus

  OutputFormatter* = ref object of RootObj

  ConsoleOutputFormatter* = ref object of OutputFormatter
    colorOutput: bool
      ## Have test results printed in color.
      ## Default is true for the non-js target,
      ## for which ``stdout`` is a tty.
      ## Setting the environment variable
      ## ``NIMTEST_COLOR`` to ``always`` or
      ## ``never`` changes the default for the
      ## non-js target to true or false respectively.
      ## The deprecated environment variable
      ## ``NIMTEST_NO_COLOR``, when set,
      ## changes the default to true, if
      ## ``NIMTEST_COLOR`` is undefined.
    outputLevel: OutputLevel
      ## Set the verbosity of test results.
      ## Default is ``PRINT_ALL``, unless
      ## the ``NIMTEST_OUTPUT_LVL`` environment
      ## variable is set for the non-js target.
    isInSuite: bool
    isInTest: bool

  JUnitOutputFormatter* = ref object of OutputFormatter
    stream: Stream
    testErrors: seq[string]
    testStartTime: float
    testStackTrace: string

var
  abortOnError* {.threadvar.}: bool ## Set to true in order to quit
                                    ## immediately on fail. Default is false,
                                    ## unless the ``NIMTEST_ABORT_ON_ERROR``
                                    ## environment variable is set for
                                    ## the non-js target.

  checkpoints {.threadvar.}: seq[string]
  formatters {.threadvar.}: seq[OutputFormatter]
  testsFilters {.threadvar.}: HashSet[string]
  disabledParamFiltering {.threadvar.}: bool

when declared(stdout):
  abortOnError = existsEnv("NIMTEST_ABORT_ON_ERROR")

method suiteStarted*(formatter: OutputFormatter, suiteName: string) {.base, gcsafe.} =
  discard
method testStarted*(formatter: OutputFormatter, testName: string) {.base, gcsafe.} =
  discard
method failureOccurred*(formatter: OutputFormatter, checkpoints: seq[string],
    stackTrace: string) {.base, gcsafe.} =
  ## ``stackTrace`` is provided only if the failure occurred due to an exception.
  ## ``checkpoints`` is never ``nil``.
  discard
method testEnded*(formatter: OutputFormatter, testResult: TestResult) {.base, gcsafe.} =
  discard
method suiteEnded*(formatter: OutputFormatter) {.base, gcsafe.} =
  discard

proc addOutputFormatter*(formatter: OutputFormatter) =
  formatters.add(formatter)

proc delOutputFormatter*(formatter: OutputFormatter) =
  keepIf(formatters, proc (x: OutputFormatter): bool =
    x != formatter)

proc resetOutputFormatters* {.since: (1, 1).} =
  formatters = @[]

proc newConsoleOutputFormatter*(outputLevel: OutputLevel = OutputLevel.PRINT_ALL,
                                colorOutput = true): <//>ConsoleOutputFormatter =
  ConsoleOutputFormatter(
    outputLevel: outputLevel,
    colorOutput: colorOutput
  )

proc defaultConsoleFormatter*(): <//>ConsoleOutputFormatter =
  when declared(stdout):
    # Reading settings
    # On a terminal this branch is executed
    var envOutLvl = os.getEnv("NIMTEST_OUTPUT_LVL").string
    var colorOutput = isatty(stdout)
    if existsEnv("NIMTEST_COLOR"):
      let colorEnv = getEnv("NIMTEST_COLOR")
      if colorEnv == "never":
        colorOutput = false
      elif colorEnv == "always":
        colorOutput = true
    elif existsEnv("NIMTEST_NO_COLOR"):
      colorOutput = false
    var outputLevel = OutputLevel.PRINT_ALL
    if envOutLvl.len > 0:
      for opt in countup(low(OutputLevel), high(OutputLevel)):
        if $opt == envOutLvl:
          outputLevel = opt
          break
    result = newConsoleOutputFormatter(outputLevel, colorOutput)
  else:
    result = newConsoleOutputFormatter()

method suiteStarted*(formatter: ConsoleOutputFormatter, suiteName: string) =
  template rawPrint() = echo("\n[Suite] ", suiteName)
  when useTerminal:
    if formatter.colorOutput:
      styledEcho styleBright, fgBlue, "\n[Suite] ", resetStyle, suiteName
    else: rawPrint()
  else: rawPrint()
  formatter.isInSuite = true

method testStarted*(formatter: ConsoleOutputFormatter, testName: string) =
  formatter.isInTest = true

method failureOccurred*(formatter: ConsoleOutputFormatter,
                        checkpoints: seq[string], stackTrace: string) =
  if stackTrace.len > 0:
    echo stackTrace
  let prefix = if formatter.isInSuite: "    " else: ""
  for msg in items(checkpoints):
    echo prefix, msg

method testEnded*(formatter: ConsoleOutputFormatter, testResult: TestResult) =
  formatter.isInTest = false

  if formatter.outputLevel != OutputLevel.PRINT_NONE and
      (formatter.outputLevel == OutputLevel.PRINT_ALL or testResult.status == TestStatus.FAILED):
    let prefix = if testResult.suiteName.len > 0: "  " else: ""
    template rawPrint() = echo(prefix, "[", $testResult.status, "] ",
        testResult.testName)
    when useTerminal:
      if formatter.colorOutput:
        var color = case testResult.status
          of TestStatus.OK: fgGreen
          of TestStatus.FAILED: fgRed
          of TestStatus.SKIPPED: fgYellow
        styledEcho styleBright, color, prefix, "[", $testResult.status, "] ",
            resetStyle, testResult.testName
      else:
        rawPrint()
    else:
      rawPrint()

method suiteEnded*(formatter: ConsoleOutputFormatter) =
  formatter.isInSuite = false

proc xmlEscape(s: string): string =
  result = newStringOfCap(s.len)
  for c in items(s):
    case c:
    of '<': result.add("&lt;")
    of '>': result.add("&gt;")
    of '&': result.add("&amp;")
    of '"': result.add("&quot;")
    of '\'': result.add("&apos;")
    else:
      if ord(c) < 32:
        result.add("&#" & $ord(c) & ';')
      else:
        result.add(c)

proc newJUnitOutputFormatter*(stream: Stream): <//>JUnitOutputFormatter =
  ## Creates a formatter that writes report to the specified stream in
  ## JUnit format.
  ## The ``stream`` is NOT closed automatically when the test are finished,
  ## because the formatter has no way to know when all tests are finished.
  ## You should invoke formatter.close() to finalize the report.
  result = JUnitOutputFormatter(
    stream: stream,
    testErrors: @[],
    testStackTrace: "",
    testStartTime: 0.0
  )
  stream.writeLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
  stream.writeLine("<testsuites>")

proc close*(formatter: JUnitOutputFormatter) =
  ## Completes the report and closes the underlying stream.
  formatter.stream.writeLine("</testsuites>")
  formatter.stream.close()

method suiteStarted*(formatter: JUnitOutputFormatter, suiteName: string) =
  formatter.stream.writeLine("\t<testsuite name=\"$1\">" % xmlEscape(suiteName))

method testStarted*(formatter: JUnitOutputFormatter, testName: string) =
  formatter.testErrors.setLen(0)
  formatter.testStackTrace.setLen(0)
  formatter.testStartTime = epochTime()

method failureOccurred*(formatter: JUnitOutputFormatter,
                        checkpoints: seq[string], stackTrace: string) =
  ## ``stackTrace`` is provided only if the failure occurred due to an exception.
  ## ``checkpoints`` is never ``nil``.
  formatter.testErrors.add(checkpoints)
  if stackTrace.len > 0:
    formatter.testStackTrace = stackTrace

method testEnded*(formatter: JUnitOutputFormatter, testResult: TestResult) =
  let time = epochTime() - formatter.testStartTime
  let timeStr = time.formatFloat(ffDecimal, precision = 8)
  formatter.stream.writeLine("\t\t<testcase name=\"$#\" time=\"$#\">" % [
      xmlEscape(testResult.testName), timeStr])
  case testResult.status
  of TestStatus.OK:
    discard
  of TestStatus.SKIPPED:
    formatter.stream.writeLine("<skipped />")
  of TestStatus.FAILED:
    let failureMsg = if formatter.testStackTrace.len > 0 and
                        formatter.testErrors.len > 0:
                       xmlEscape(formatter.testErrors[^1])
                     elif formatter.testErrors.len > 0:
                       xmlEscape(formatter.testErrors[0])
                     else: "The test failed without outputting an error"

    var errs = ""
    if formatter.testErrors.len > 1:
      var startIdx = if formatter.testStackTrace.len > 0: 0 else: 1
      var endIdx = if formatter.testStackTrace.len > 0:
          formatter.testErrors.len - 2
        else: formatter.testErrors.len - 1

      for errIdx in startIdx..endIdx:
        if errs.len > 0:
          errs.add("\n")
        errs.add(xmlEscape(formatter.testErrors[errIdx]))

    if formatter.testStackTrace.len > 0:
      formatter.stream.writeLine("\t\t\t<error message=\"$#\">$#</error>" % [
          failureMsg, xmlEscape(formatter.testStackTrace)])
      if errs.len > 0:
        formatter.stream.writeLine("\t\t\t<system-err>$#</system-err>" % errs)
    else:
      formatter.stream.writeLine("\t\t\t<failure message=\"$#\">$#</failure>" %
          [failureMsg, errs])

  formatter.stream.writeLine("\t\t</testcase>")

method suiteEnded*(formatter: JUnitOutputFormatter) =
  formatter.stream.writeLine("\t</testsuite>")

proc glob(matcher, filter: string): bool =
  ## Globbing using a single `*`. Empty `filter` matches everything.
  if filter.len == 0:
    return true

  if not filter.contains('*'):
    return matcher == filter

  let beforeAndAfter = filter.split('*', maxsplit = 1)
  if beforeAndAfter.len == 1:
    # "foo*"
    return matcher.startsWith(beforeAndAfter[0])

  if matcher.len < filter.len - 1:
    return false # "12345" should not match "123*345"

  return matcher.startsWith(beforeAndAfter[0]) and matcher.endsWith(
      beforeAndAfter[1])

proc matchFilter(suiteName, testName, filter: string): bool =
  if filter == "":
    return true
  if testName == filter:
    # corner case for tests containing "::" in their name
    return true
  let suiteAndTestFilters = filter.split("::", maxsplit = 1)

  if suiteAndTestFilters.len == 1:
    # no suite specified
    let testFilter = suiteAndTestFilters[0]
    return glob(testName, testFilter)

  return glob(suiteName, suiteAndTestFilters[0]) and
         glob(testName, suiteAndTestFilters[1])

when defined(testing): export matchFilter

proc shouldRun(currentSuiteName, testName: string): bool =
  ## Check if a test should be run by matching suiteName and testName against
  ## test filters.
  if testsFilters.len == 0:
    return true

  for f in testsFilters:
    if matchFilter(currentSuiteName, testName, f):
      return true

  return false

proc ensureInitialized() =
  if formatters.len == 0:
    formatters = @[OutputFormatter(defaultConsoleFormatter())]

  if not disabledParamFiltering and not testsFilters.isValid:
    testsFilters.init()
    when declared(paramCount):
      # Read tests to run from the command line.
      for i in 1 .. paramCount():
        testsFilters.incl(paramStr(i))

# These two procs are added as workarounds for
# https://github.com/nim-lang/Nim/issues/5549
proc suiteEnded() =
  for formatter in formatters:
    formatter.suiteEnded()

proc testEnded(testResult: TestResult) =
  for formatter in formatters:
    formatter.testEnded(testResult)

template suite*(name, body) {.dirty.} =
  ## Declare a test suite identified by `name` with optional ``setup``
  ## and/or ``teardown`` section.
  ##
  ## A test suite is a series of one or more related tests sharing a
  ## common fixture (``setup``, ``teardown``). The fixture is executed
  ## for EACH test.
  ##
  ## .. code-block:: nim
  ##  suite "test suite for addition":
  ##    setup:
  ##      let result = 4
  ##
  ##    test "2 + 2 = 4":
  ##      check(2+2 == result)
  ##
  ##    test "(2 + -2) != 4":
  ##      check(2 + -2 != result)
  ##
  ##    # No teardown needed
  ##
  ## The suite will run the individual test cases in the order in which
  ## they were listed. With default global settings the above code prints:
  ##
  ## .. code-block::
  ##
  ##  [Suite] test suite for addition
  ##    [OK] 2 + 2 = 4
  ##    [OK] (2 + -2) != 4
  bind formatters, ensureInitialized, suiteEnded

  block:
    template setup(setupBody: untyped) {.dirty, used.} =
      var testSetupIMPLFlag {.used.} = true
      template testSetupIMPL: untyped {.dirty.} = setupBody

    template teardown(teardownBody: untyped) {.dirty, used.} =
      var testTeardownIMPLFlag {.used.} = true
      template testTeardownIMPL: untyped {.dirty.} = teardownBody

    let testSuiteName {.used.} = name

    ensureInitialized()
    try:
      for formatter in formatters:
        formatter.suiteStarted(name)
      body
    finally:
      suiteEnded()

template exceptionTypeName(e: typed): string = $e.name

template test*(name, body) {.dirty.} =
  ## Define a single test case identified by `name`.
  ##
  ## .. code-block:: nim
  ##
  ##  test "roses are red":
  ##    let roses = "red"
  ##    check(roses == "red")
  ##
  ## The above code outputs:
  ##
  ## .. code-block::
  ##
  ##  [OK] roses are red
  bind shouldRun, checkpoints, formatters, ensureInitialized, testEnded, exceptionTypeName

  ensureInitialized()

  if shouldRun(when declared(testSuiteName): testSuiteName else: "", name):
    checkpoints = @[]
    var testStatusIMPL {.inject.} = TestStatus.OK

    for formatter in formatters:
      formatter.testStarted(name)

    try:
      when declared(testSetupIMPLFlag): testSetupIMPL()
      when declared(testTeardownIMPLFlag):
        defer: testTeardownIMPL()
      body

    except:
      let e = getCurrentException()
      let eTypeDesc = "[" & exceptionTypeName(e) & "]"
      checkpoint("Unhandled exception: " & getCurrentExceptionMsg() & " " & eTypeDesc)
      var stackTrace {.inject.} = e.getStackTrace()
      fail()

    finally:
      if testStatusIMPL == TestStatus.FAILED:
        programResult = 1
      let testResult = TestResult(
        suiteName: when declared(testSuiteName): testSuiteName else: "",
        testName: name,
        status: testStatusIMPL
      )
      testEnded(testResult)
      checkpoints = @[]

proc checkpoint*(msg: string) =
  ## Set a checkpoint identified by `msg`. Upon test failure all
  ## checkpoints encountered so far are printed out. Example:
  ##
  ## .. code-block:: nim
  ##
  ##  checkpoint("Checkpoint A")
  ##  check((42, "the Answer to life and everything") == (1, "a"))
  ##  checkpoint("Checkpoint B")
  ##
  ## outputs "Checkpoint A" once it fails.
  checkpoints.add(msg)
  # TODO: add support for something like SCOPED_TRACE from Google Test

template fail* =
  ## Print out the checkpoints encountered so far and quit if ``abortOnError``
  ## is true. Otherwise, erase the checkpoints and indicate the test has
  ## failed (change exit code and test status). This template is useful
  ## for debugging, but is otherwise mostly used internally. Example:
  ##
  ## .. code-block:: nim
  ##
  ##  checkpoint("Checkpoint A")
  ##  complicatedProcInThread()
  ##  fail()
  ##
  ## outputs "Checkpoint A" before quitting.
  bind ensureInitialized

  when declared(testStatusIMPL):
    testStatusIMPL = TestStatus.FAILED
  else:
    programResult = 1

  ensureInitialized()

    # var stackTrace: string = nil
  for formatter in formatters:
    when declared(stackTrace):
      formatter.failureOccurred(checkpoints, stackTrace)
    else:
      formatter.failureOccurred(checkpoints, "")

  when declared(programResult):
    if abortOnError: quit(programResult)

  checkpoints = @[]

template skip* =
  ## Mark the test as skipped. Should be used directly
  ## in case when it is not possible to perform test
  ## for reasons depending on outer environment,
  ## or certain application logic conditions or configurations.
  ## The test code is still executed.
  ##
  ## .. code-block:: nim
  ##
  ##  if not isGLContextCreated():
  ##    skip()
  bind checkpoints

  testStatusIMPL = TestStatus.SKIPPED
  checkpoints = @[]

macro check*(conditions: untyped): untyped =
  ## Verify if a statement or a list of statements is true.
  ## A helpful error message and set checkpoints are printed out on
  ## failure (if ``outputLevel`` is not ``PRINT_NONE``).
  ## Example:
  ##
  ## .. code-block:: nim
  ##
  ##  import strutils
  ##
  ##  check("AKB48".toLowerAscii() == "akb48")
  ##
  ##  let teams = {'A', 'K', 'B', '4', '8'}
  ##
  ##  check:
  ##    "AKB48".toLowerAscii() == "akb48"
  ##    'C' in teams
  let checked = callsite()[1]

  template asgn(a: untyped, value: typed) =
    var a = value # XXX: we need "var: var" here in order to
                  # preserve the semantics of var params

  template print(name: untyped, value: typed) =
    when compiles(string($value)):
      checkpoint(name & " was " & $value)

  proc inspectArgs(exp: NimNode): tuple[assigns, check, printOuts: NimNode] =
    result.check = copyNimTree(exp)
    result.assigns = newNimNode(nnkStmtList)
    result.printOuts = newNimNode(nnkStmtList)

    var counter = 0

    if exp[0].kind in {nnkIdent, nnkOpenSymChoice, nnkClosedSymChoice, nnkSym} and
        $exp[0] in ["not", "in", "notin", "==", "<=",
                    ">=", "<", ">", "!=", "is", "isnot"]:

      for i in 1 ..< exp.len:
        if exp[i].kind notin nnkLiterals:
          inc counter
          let argStr = exp[i].toStrLit
          let paramAst = exp[i]
          if exp[i].kind == nnkIdent:
            result.printOuts.add getAst(print(argStr, paramAst))
          if exp[i].kind in nnkCallKinds + {nnkDotExpr, nnkBracketExpr}:
            let callVar = newIdentNode(":c" & $counter)
            result.assigns.add getAst(asgn(callVar, paramAst))
            result.check[i] = callVar
            result.printOuts.add getAst(print(argStr, callVar))
          if exp[i].kind == nnkExprEqExpr:
            # ExprEqExpr
            #   Ident !"v"
            #   IntLit 2
            result.check[i] = exp[i][1]
          if exp[i].typeKind notin {ntyTypeDesc}:
            let arg = newIdentNode(":p" & $counter)
            result.assigns.add getAst(asgn(arg, paramAst))
            result.printOuts.add getAst(print(argStr, arg))
            if exp[i].kind != nnkExprEqExpr:
              result.check[i] = arg
            else:
              result.check[i][1] = arg

  case checked.kind
  of nnkCallKinds:

    let (assigns, check, printOuts) = inspectArgs(checked)
    let lineinfo = newStrLitNode(checked.lineInfo)
    let callLit = checked.toStrLit
    result = quote do:
      block:
        `assigns`
        if not `check`:
          checkpoint(`lineinfo` & ": Check failed: " & `callLit`)
          `printOuts`
          fail()

  of nnkStmtList:
    result = newNimNode(nnkStmtList)
    for node in checked:
      if node.kind != nnkCommentStmt:
        result.add(newCall(!"check", node))

  else:
    let lineinfo = newStrLitNode(checked.lineInfo)
    let callLit = checked.toStrLit

    result = quote do:
      if not `checked`:
        checkpoint(`lineinfo` & ": Check failed: " & `callLit`)
        fail()

template require*(conditions: untyped) =
  ## Same as `check` except any failed test causes the program to quit
  ## immediately. Any teardown statements are not executed and the failed
  ## test output is not generated.
  let savedAbortOnError = abortOnError
  block:
    abortOnError = true
    check conditions
  abortOnError = savedAbortOnError

macro expect*(exceptions: varargs[typed], body: untyped): untyped =
  ## Test if `body` raises an exception found in the passed `exceptions`.
  ## The test passes if the raised exception is part of the acceptable
  ## exceptions. Otherwise, it fails.
  ## Example:
  ##
  ## .. code-block:: nim
  ##
  ##  import math, random
  ##  proc defectiveRobot() =
  ##    randomize()
  ##    case random(1..4)
  ##    of 1: raise newException(OSError, "CANNOT COMPUTE!")
  ##    of 2: discard parseInt("Hello World!")
  ##    of 3: raise newException(IOError, "I can't do that Dave.")
  ##    else: assert 2 + 2 == 5
  ##
  ##  expect IOError, OSError, ValueError, AssertionDefect:
  ##    defectiveRobot()
  let exp = callsite()
  template expectBody(errorTypes, lineInfoLit, body): NimNode {.dirty.} =
    try:
      body
      checkpoint(lineInfoLit & ": Expect Failed, no exception was thrown.")
      fail()
    except errorTypes:
      discard
    except:
      checkpoint(lineInfoLit & ": Expect Failed, unexpected exception was thrown.")
      fail()

  var body = exp[exp.len - 1]

  var errorTypes = newNimNode(nnkBracket)
  for i in countup(1, exp.len - 2):
    errorTypes.add(exp[i])

  result = getAst(expectBody(errorTypes, exp.lineInfo, body))

proc disableParamFiltering* =
  ## disables filtering tests with the command line params
  disabledParamFiltering = true
8bf73cd34480d907'>1bba641fe ^
3f3dda5a7 ^


dbf9117c5 ^
8b2a9401a ^
e792940f5 ^


1b20f768c ^

0cae8ef2c ^
1b20f768c ^
1bba641fe ^
1dd9ec85b ^
04520c0ce ^
b2c5d7b4f ^
e0e1241a5 ^
db4f617af ^
0e7f2ca3f ^


1b20f768c ^


0a2f711b9 ^
1b20f768c ^
3a62cf29d ^
1b20f768c ^


07b355bea ^
04520c0ce ^
5bed7d282 ^

9344e9fbf ^


1b20f768c ^
83ae70cb5 ^
ad503ce8f ^
0872e7a27 ^

0e7f2ca3f ^
d79a5f527 ^

3260702a6 ^
04520c0ce ^
0cae8ef2c ^
a404ec540 ^
04520c0ce ^
5bed7d282 ^


1bba641fe ^

6deda5a97 ^
a9ba02e8c ^

f45a2f23b ^
1b20f768c ^


1bba641fe ^


84a71dad8 ^
83ae70cb5 ^
84a71dad8 ^
e3037a2f3 ^
0cae8ef2c ^
83ae70cb5 ^
e3037a2f3 ^
1b20f768c ^


4d2486c85 ^
e792940f5 ^


afbff2d50 ^

286e5958d ^
afbff2d50 ^
44ceefa9f ^
afbff2d50 ^
e792940f5 ^
755225d0e ^
eca05d2a3 ^





286e5958d ^
eca05d2a3 ^
286e5958d ^
eca05d2a3 ^
286e5958d ^
ddb718548 ^
286e5958d ^
ddb718548 ^
eca05d2a3 ^

5bed7d282 ^






8b2a9401a ^


765366c1f ^
8b2a9401a ^

baf72691c ^
0cae8ef2c ^
afbff2d50 ^

2b56335e1 ^

a404ec540 ^

afbff2d50 ^






9ac062b74 ^

afbff2d50 ^
72bbd07ec ^
765366c1f ^




765366c1f ^

afbff2d50 ^







1bba641fe ^
afbff2d50 ^

afbff2d50 ^

b7e8daf65 ^


1dd9ec85b ^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593


                    

                      
                      
 

                          
             
 
                                                                                   
 
                                                                            


                                                                        

                                                                         





                                                                    
 


              
 

                 
 


                                                                          
                                                                              

                
                           
                                                                               
                                                            
 
                                             
                                                                        
                                                                                  




    


                                                                     
                         
                                                              








                                                                                
 
                       
                                        
 

                                                                                
 
                         
                                                                   
 


                          
                             
                                                              



                                                                           


                                                                     

 

          
 
                               
                                                                                   
 
                               
                                                              
 
                             
                                                               
                                                          
 
                             
                                                             
 





                                                                
                                                                        
 

                                         
                                             

                               
                                                                                      
 

                                                                
 


                                                                      
 

                                                 
 
                                 

                                                                    
                     
                       
 
                         
                                                                            

 


               
                               
                                   
 
                                     




                                                                            
                                                  











                                                                                 
                                                    



                                                               
 
                               
                                                                   
                     
 



                                                                      
                             
                                                                                
 
                           
                                                                           
                                                                          
                          
 




                                                                      
                           
                                                                    
 



                                                                        
                             
                                                                 
 
 

             
 
                               
                                                         
 
                       
                                                            
 



                                 




                                                                            
                                                    
                                                                                    




                                                                             
                                                                       


                             
                                                                       

                                     


                                                                          
                
 
                         
                                                            
 

                                                                          

                                                                    


                                                                       

                                                                     

                                                    
 

              
 
                           
                                                                              
 

                                                                     
                                           
 


                                                   


                                        
                               
                                                                               
 
                       
                       
 
                     
                               
 


                                                         
 


                              




                                                                      
                  

                                         
                                                                        


                                           
                                                                         


                             
                                                                          


                                     
                                                                      
 
                   

                                                      

                                                                       
 
                                 

                                                                             
 


                                              

                                                 

                   
                                                                  
                   
 

                                                                          
                                                                  
 
                     
                                              








                                                       
                                                                          
 
 

       
 



                                                                              
                               
 
                               

                                                                          
                           
                                                                             
                                                                             
 
                             
                                                                        
                                                                            
                                                                          
                                                                               
                                     
 
                             
                                                                        
 


                                                                                                                                         
                             
                                                                
 
                             
                                                                        
 
                             
                                                                             
                                                                            

                                                                             
 


        
 
                                               
                                                                    
                                                                   

                                                        
                                     
                                                                  
                                                                               
 
                                           

                                                                
                                           

                                                                         
 


              
                           
                                                                     
                                                
 
                               
                                                                             
 


          
 
                           

                                                                  
                                                       
 
 



                         
                                                      


                                                                          
            
 


                                                    

                                                     
                                                                          
                                                                             
                                                                              
 
                     
                                                      
 
 


             


                                                                       
 
                         
                                                


                                                        
 
                               

                                                                                 


                                         
                               
                                                                          
 

                                                                          
 

                                
 
                           
                                                                  
 
                     


                                                                     

                          
 

                                                                     
 


                                                              


                               
                               
                                   
 
                         
                                                                                  
                                                                        
 


                                                          
 


                

                   
 
                 
                                                                    
                                                    
 
 





                                                                               
 
                             
                                                                          
                          
 
                               
                                                                           
                          

 






                                                   


        
                                                                   

                                                                         
 
                

                

                                                         

                             






                                            

                                                                            
 
 




                               

 







                                            
                                          

                               

 


                                          

                           
====================
Nim Standard Library
====================

:Author: Andreas Rumpf
:Version: |nimversion|

.. default-role:: code
.. include:: rstcommon.rst
.. contents::

Nim's library is divided into *pure libraries*, *impure libraries*, and *wrappers*.

Pure libraries do not depend on any external ``*.dll`` or ``lib*.so`` binary
while impure libraries do. A wrapper is an impure library that is a very
low-level interface to a C library.

Read this `document <apis.html>`_ for a quick overview of the API design.


Nimble
======

Nim's standard library only covers the basics, check
out `<https://nimble.directory/>`_ for a list of 3rd party packages.


Pure libraries
==============

Automatic imports
-----------------

* `system <system.html>`_
  Basic procs and operators that every program needs. It also provides IO
  facilities for reading and writing text and binary files. It is imported
  implicitly by the compiler. Do not import it directly. It relies on compiler
  magic to work.

* `threads <threads.html>`_
  Basic Nim thread support. **Note:** This is part of the system module. Do not
  import it explicitly. Enabled with `--threads:on`:option:.

* `channels_builtin <channels_builtin.html>`_
  Nim message passing support for threads. **Note:** This is part of the
  system module. Do not import it explicitly. Enabled with `--threads:on`:option:.


Core
----

* `atomics <atomics.html>`_
  Types and operations for atomic operations and lockless algorithms.

* `bitops <bitops.html>`_
  Provides a series of low-level methods for bit manipulation.

* `cpuinfo <cpuinfo.html>`_
  This module implements procs to determine the number of CPUs / cores.

* `endians <endians.html>`_
  This module contains helpers that deal with different byte orders.

* `lenientops <lenientops.html>`_
  Provides binary operators for mixed integer/float expressions for convenience.

* `locks <locks.html>`_
  Locks and condition variables for Nim.

* `macrocache <macrocache.html>`_
  Provides an API for macros to collect compile-time information across modules.

* `macros <macros.html>`_
  Contains the AST API and documentation of Nim for writing macros.

* `rlocks <rlocks.html>`_
  Reentrant locks for Nim.

* `typeinfo <typeinfo.html>`_
  Provides (unsafe) access to Nim's run-time type information.

* `typetraits <typetraits.html>`_
  This module defines compile-time reflection procs for working with types.

* `volatile <volatile.html>`_
  This module contains code for generating volatile loads and stores,
  which are useful in embedded and systems programming.


Algorithms
----------

* `algorithm <algorithm.html>`_
  This module implements some common generic algorithms like sort or binary search.

* `enumutils <enumutils.html>`_
  This module adds functionality for the built-in `enum` type.

* `sequtils <sequtils.html>`_
  This module implements operations for the built-in `seq` type
  which were inspired by functional programming languages.

* `setutils <setutils.html>`_
  This module adds functionality for the built-in `set` type.


Collections
-----------

* `critbits <critbits.html>`_
  This module implements a *crit bit tree* which is an efficient
  container for a sorted set of strings, or a sorted mapping of strings.

* `deques <deques.html>`_
  Implementation of a double-ended queue.
  The underlying implementation uses a `seq`.

* `heapqueue <heapqueue.html>`_
  Implementation of a binary heap data structure that can be used as a priority queue.

* `intsets <intsets.html>`_
  Efficient implementation of a set of ints as a sparse bit set.

* `lists <lists.html>`_
  Nim linked list support. Contains singly and doubly linked lists and
  circular lists ("rings").

* `options <options.html>`_
  The option type encapsulates an optional value.

* `packedsets <packedsets.html>`_
  Efficient implementation of a set of ordinals as a sparse bit set.

* `sets <sets.html>`_
  Nim hash set support.

* `tables <tables.html>`_
  Nim hash table support. Contains tables, ordered tables, and count tables.


String handling
---------------

* `cstrutils <cstrutils.html>`_
  Utilities for `cstring` handling.

* `editdistance <editdistance.html>`_
  This module contains an algorithm to compute the edit distance between two
  Unicode strings.

* `encodings <encodings.html>`_
  Converts between different character encodings. On UNIX, this uses
  the `iconv` library, on Windows the Windows API.

* `parseutils <parseutils.html>`_
  This module contains helpers for parsing tokens, numbers, identifiers, etc.

* `pegs <pegs.html>`_
  This module contains procedures and operators for handling PEGs.

* `punycode <punycode.html>`_
  Implements a representation of Unicode with the limited ASCII character subset.

* `ropes <ropes.html>`_
  This module contains support for a *rope* data type.
  Ropes can represent very long strings efficiently;
  in particular, concatenation is done in O(1) instead of O(n).

* `strbasics <strbasics.html>`_
  This module provides some high performance string operations.

* `strformat <strformat.html>`_
  Macro based standard string interpolation/formatting. Inspired by
  Python's f-strings.

* `strmisc <strmisc.html>`_
  This module contains uncommon string handling operations that do not
  fit with the commonly used operations in strutils.

* `strscans <strscans.html>`_
  This module contains a `scanf` macro for convenient parsing of mini languages.

* `strtabs <strtabs.html>`_
  The `strtabs` module implements an efficient hash table that is a mapping
  from strings to strings. Supports a case-sensitive, case-insensitive and
  style-insensitive modes.

* `strutils <strutils.html>`_
  This module contains common string handling operations like changing
  case of a string, splitting a string into substrings, searching for
  substrings, replacing substrings.

* `unicode <unicode.html>`_
  This module provides support to handle the Unicode UTF-8 encoding.

* `unidecode <unidecode.html>`_
  It provides a single proc that does Unicode to ASCII transliterations.
  Based on Python's Unidecode module.

* `wordwrap <wordwrap.html>`_
  This module contains an algorithm to wordwrap a Unicode string.


Time handling
-------------

* `monotimes <monotimes.html>`_
  The `monotimes` module implements monotonic timestamps.

* `times <times.html>`_
  The `times` module contains support for working with time.


Generic Operating System Services
---------------------------------

* `distros <distros.html>`_
  This module implements the basics for OS distribution ("distro") detection
  and the OS's native package manager.
  Its primary purpose is to produce output for Nimble packages,
  but it also contains the widely used **Distribution** enum
  that is useful for writing platform-specific code.
  See `packaging <packaging.html>`_ for hints on distributing Nim using OS packages.

* `dynlib <dynlib.html>`_
  This module implements the ability to access symbols from shared libraries.

* `marshal <marshal.html>`_
  Contains procs for serialization and deserialization of arbitrary Nim
  data structures.

* `memfiles <memfiles.html>`_
  This module provides support for memory-mapped files (Posix's `mmap`)
  on the different operating systems.

* `os <os.html>`_
  Basic operating system facilities like retrieving environment variables,
  reading command line arguments, working with directories, running shell
  commands, etc.

* `osproc <osproc.html>`_
  Module for process communication beyond `os.execShellCmd`.

* `streams <streams.html>`_
  This module provides a stream interface and two implementations thereof:
  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.

* `terminal <terminal.html>`_
  This module contains a few procedures to control the *terminal*
  (also called *console*). The implementation simply uses ANSI escape
  sequences and does not depend on any other module.


Math libraries
--------------

* `complex <complex.html>`_
  This module implements complex numbers and relevant mathematical operations.

* `fenv <fenv.html>`_
  Floating-point environment. Handling of floating-point rounding and
  exceptions (overflow, zero-divide, etc.).

* `math <math.html>`_
  Mathematical operations like cosine, square root.

* `random <random.html>`_
  Fast and tiny random number generator.

* `rationals <rationals.html>`_
  This module implements rational numbers and relevant mathematical operations.

* `stats <stats.html>`_
  Statistical analysis.

* `sums <sums.html>`_
  Accurate summation functions.

* `sysrand <sysrand.html>`_
  Cryptographically secure pseudorandom number generator.


Internet Protocols and Support
------------------------------

* `asyncdispatch <asyncdispatch.html>`_
  This module implements an asynchronous dispatcher for IO operations.

* `asyncfile <asyncfile.html>`_
  This module implements asynchronous file reading and writing using
  `asyncdispatch`.

* `asyncftpclient <asyncftpclient.html>`_
  This module implements an asynchronous FTP client using the `asyncnet`
  module.

* `asynchttpserver <asynchttpserver.html>`_
  This module implements an asynchronous HTTP server using the `asyncnet`
  module.

* `asyncnet <asyncnet.html>`_
  This module implements asynchronous sockets based on the `asyncdispatch`
  module.

* `asyncstreams <asyncstreams.html>`_
  This module provides `FutureStream` - a future that acts as a queue.

* `cgi <cgi.html>`_
  This module implements helpers for CGI applications.

* `cookies <cookies.html>`_
  This module contains helper procs for parsing and generating cookies.

* `httpclient <httpclient.html>`_
  This module implements a simple HTTP client which supports both synchronous
  and asynchronous retrieval of web pages.

* `mimetypes <mimetypes.html>`_
  This module implements a mimetypes database.

* `nativesockets <nativesockets.html>`_
  This module implements a low-level sockets API.

* `net <net.html>`_
  This module implements a high-level sockets API. It replaces the
  `sockets` module.

* `selectors <selectors.html>`_
  This module implements a selector API with backends specific to each OS.
  Currently, epoll on Linux and select on other operating systems.

* `smtp <smtp.html>`_
  This module implements a simple SMTP client.

* `uri <uri.html>`_
  This module provides functions for working with URIs.


Threading
---------

* `threadpool <threadpool.html>`_
  Implements Nim's `spawn <manual_experimental.html#parallel-amp-spawn>`_.


Parsers
-------

* `htmlparser <htmlparser.html>`_
  This module parses an HTML document and creates its XML tree representation.

* `json <json.html>`_
  High-performance JSON parser.

* `jsonutils <jsonutils.html>`_
  This module implements a hookable (de)serialization for arbitrary types.

* `lexbase <lexbase.html>`_
  This is a low-level module that implements an extremely efficient buffering
  scheme for lexers and parsers. This is used by the diverse parsing modules.

* `parsecfg <parsecfg.html>`_
  The `parsecfg` module implements a high-performance configuration file
  parser. The configuration file's syntax is similar to the Windows ``.ini``
  format, but much more powerful, as it is not a line based parser. String
  literals, raw string literals, and triple quote string literals are supported
  as in the Nim programming language.

* `parsecsv <parsecsv.html>`_
  The `parsecsv` module implements a simple high-performance CSV parser.

* `parsejson <parsejson.html>`_
  This module implements a JSON parser. It is used and exported by the `json <json.html>`_ module, but can also be used in its own right.

* `parseopt <parseopt.html>`_
  The `parseopt` module implements a command line option parser.

* `parsesql <parsesql.html>`_
  The `parsesql` module implements a simple high-performance SQL parser.

* `parsexml <parsexml.html>`_
  The `parsexml` module implements a simple high performance XML/HTML parser.
  The only encoding that is supported is UTF-8. The parser has been designed
  to be somewhat error-correcting, so that even some "wild HTML" found on the
  web can be parsed with it.


Docutils
--------

* `packages/docutils/highlite <highlite.html>`_
  Source highlighter for programming or markup languages. Currently,
  only a few languages are supported, other languages may be added.
  The interface supports one language nested in another.

* `packages/docutils/rst <rst.html>`_
  This module implements a reStructuredText parser. A large subset
  is implemented. Some features of the markdown wiki syntax are also supported.

* `packages/docutils/rstast <rstast.html>`_
  This module implements an AST for the reStructuredText parser.

* `packages/docutils/rstgen <rstgen.html>`_
  This module implements a generator of HTML/Latex from reStructuredText.


XML Processing
--------------

* `xmltree <xmltree.html>`_
  A simple XML tree. More efficient and simpler than the DOM. It also
  contains a macro for XML/HTML code generation.

* `xmlparser <xmlparser.html>`_
  This module parses an XML document and creates its XML tree representation.


Generators
----------

* `htmlgen <htmlgen.html>`_
  This module implements a simple XML and HTML code
  generator. Each commonly used HTML tag has a corresponding macro
  that generates a string with its HTML representation.


Hashing
-------

* `base64 <base64.html>`_
  This module implements a Base64 encoder and decoder.

* `hashes <hashes.html>`_
  This module implements efficient computations of hash values for diverse
  Nim types.

* `md5 <md5.html>`_
  This module implements the MD5 checksum algorithm.

* `oids <oids.html>`_
  An OID is a global ID that consists of a timestamp,
  a unique counter, and a random value. This combination should suffice to
  produce a globally distributed unique ID. This implementation was extracted
  from the MongoDB interface and it thus binary compatible with a MongoDB OID.

* `sha1 <sha1.html>`_
  This module implements the SHA-1 checksum algorithm.


Miscellaneous
-------------

* `browsers <browsers.html>`_
  This module implements procs for opening URLs with the user's default
  browser.

* `colors <colors.html>`_
  This module implements color handling for Nim.

* `coro <coro.html>`_
  This module implements experimental coroutines in Nim.

* `enumerate <enumerate.html>`_
  This module implements `enumerate` syntactic sugar based on Nim's macro system.

* `logging <logging.html>`_
  This module implements a simple logger.

* `segfaults <segfaults.html>`_
  Turns access violations or segfaults into a `NilAccessDefect` exception.

* `sugar <sugar.html>`_
  This module implements nice syntactic sugar based on Nim's macro system.

* `unittest <unittest.html>`_
  Implements a Unit testing DSL.

* `varints <varints.html>`_
  Decode variable-length integers that are compatible with SQLite.

* `with <with.html>`_
  This module implements the `with` macro for easy function chaining.


Modules for the JS backend
--------------------------

* `asyncjs <asyncjs.html>`_
  Types and macros for writing asynchronous procedures in JavaScript.

* `dom <dom.html>`_
  Declaration of the Document Object Model for the JS backend.

* `jsbigints <jsbigints.html>`_
  Arbitrary precision integers.

* `jsconsole <jsconsole.html>`_
  Wrapper for the `console` object.

* `jscore <jscore.html>`_
  The wrapper of core JavaScript functions. For most purposes, you should be using
  the `math`, `json`, and `times` stdlib modules instead of this module.

* `jsffi <jsffi.html>`_
  Types and macros for easier interaction with JavaScript.


Impure libraries
================

Regular expressions
-------------------

* `re <re.html>`_
  This module contains procedures and operators for handling regular
  expressions. The current implementation uses PCRE.


Database support
----------------

* `db_postgres <db_postgres.html>`_
  A higher level PostgreSQL database wrapper. The same interface is implemented
  for other databases too.

* `db_mysql <db_mysql.html>`_
  A higher level MySQL database wrapper. The same interface is implemented
  for other databases too.

* `db_sqlite <db_sqlite.html>`_
  A higher level SQLite database wrapper. The same interface is implemented
  for other databases too.


Generic Operating System Services
---------------------------------

* `rdstdin <rdstdin.html>`_
  This module contains code for reading from stdin.


Wrappers
========

The generated HTML for some of these wrappers is so huge that it is
not contained in the distribution. You can then find them on the website.


Windows-specific
----------------

* `winlean <winlean.html>`_
  Contains a wrapper for a small subset of the Win32 API.
* `registry <registry.html>`_
  Windows registry support.


UNIX specific
-------------

* `posix <posix.html>`_
  Contains a wrapper for the POSIX standard.
* `posix_utils <posix_utils.html>`_
  Contains helpers for the POSIX standard or specialized for Linux and BSDs.


Regular expressions
-------------------

* `pcre <pcre.html>`_
  Wrapper for the PCRE library.


Database support
----------------

* `postgres <postgres.html>`_
  Contains a wrapper for the PostgreSQL API.
* `mysql <mysql.html>`_
  Contains a wrapper for the mySQL API.
* `sqlite3 <sqlite3.html>`_
  Contains a wrapper for the SQLite 3 API.
* `odbcsql <odbcsql.html>`_
  interface to the ODBC driver.


Network Programming and Internet Protocols
------------------------------------------

* `openssl <openssl.html>`_
  Wrapper for OpenSSL.